Wednesday, January 14, 2015

Using Models in MVC Beginners Step

We earlier saw how to Create a simple application in MVC but we did not use Models .
Let see how do we use it here.

In the Solution explorer we find a folder called Model. inside that Create a class .

here im creating a class Called CustomerModel and placing some members insde it like this

   public class CustomerModel
    {
        public int CustCode { get; set; }
        public string CustName { get; set; }
        public double Amount { get; set; }



    }

next we will create a controller called DisplayCustomerController . we obviously have to place an Actionresult under which we set the values to the object properties 

now suppose we want to have multiple customer data we create a List and add items to it 
and then return a view with the List object as a parameter

  public ActionResult CustomerModel()
        {
            CustomerModel objCust=new CustomerModel();
            objCust.CustCode=1;
            objCust.CustName="Supreet";
            objCust.Amount=100.00;

            CustomerModel objCust2 = new CustomerModel();
            objCust2.CustCode = 2;
            objCust2.CustName = "Alex";
            objCust2.Amount = 200.50;

            List<CustomerModel> objCustList = new List<CustomerModel>();
            objCustList.Add(objCust);
            objCustList.Add(objCust2);
            return View(objCustList.AsEnumerable());
        }
Finally we create a view . to do that we right click the action method and say Add View .
remeber to select List option from the Template dropdown and select the appropriate Model class from the dropdown 


now the last thing you need to do inside view is to display customer details . 
Follow the coding below 
when i created a cshtml file all coding was already there i just had to manipulate here and there
<table class="table">
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.CustCode)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.CustName)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Amount)
            </th>
          
        </tr>
   
    @foreach (var item in Model) {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.CustCode)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.CustName)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Amount)
            </td>
            <td>
                @Html.ActionLink("Edit", "Edit", new { id=item.CustCode  }) |
                @Html.ActionLink("Details", "Details", new { id = item.CustCode }) |
                @Html.ActionLink("Delete", "Delete", new { id = item.CustCode })
            </td>
            <th></th>
        </tr>
      
    }
   
    </table>

run the solution and you will see customer details populated 


Cool isn't it ?? in the next blog i will write about how various HTML controls like textbox, buttons,labels can be used .

Keep Learning Keep acheiving 
Cheers
Supreet 

Tuesday, January 13, 2015

Deleting MongoDB Records using Gridview

So far we have seen select and insert Operations .
we now see how we can perform delete operation.
Place a check box control in the gridview like below



<asp:GridView ID="gvShowTasks" runat="server" CssClass="table table-striped table-bordered table-hover" OnRowCancelingEdit="gvShowTasks_RowCancelingEdit" OnRowEditing="gvShowTasks_RowEditing"  DataKeyNames="Id" OnRowUpdating="gvShowTasks_RowUpdating">
                   <Columns>
                       <asp:TemplateField>
                           <ItemTemplate>
                               <asp:CheckBox ID="chk" runat="server" />
                           </ItemTemplate>
                       </asp:TemplateField>
                       <asp:CommandField ShowEditButton="true" />
                   </Columns>
               </asp:GridView>


on the Code Behind Place the below code in the Delete button click event



protected void btnDelete_Click(object sender, EventArgs e)
    {
        MongoClient monClient = new MongoClient("mongodb://localhost");
        MongoServer ms = monClient.GetServer();
        ms.Connect();
        MongoDatabase db = ms.GetDatabase("testdb");
        MongoCollection collection = db.GetCollection<Tasks>("Tasks");
        Tasks tsk = new Tasks();

        foreach (GridViewRow gvr in gvShowTasks.Rows)
        {
            var rowIndex = gvr.RowIndex;
            var TaskID = gvShowTasks.DataKeys[rowIndex].Values["Id"].ToString();// capturing object id for deletion
            var rowVal = gvShowTasks.Rows[rowIndex].Cells[3].Text;
            CheckBox chk = (CheckBox)gvr.FindControl("chk");
          if (chk.Checked)
          {
              ObjectId bsonId=(ObjectId.Parse(TaskID));//converting string to object id
              IMongoQuery query = Query.EQ("_id", bsonId);
              collection.Remove(query);
             

          }
           
           
        }
        var ShowTasks = collection.FindAllAs<Tasks>().ToList<Tasks>(); //Queries the tasks collection and Converts to List           
        gvShowTasks.DataSource = ShowTasks;//Set the List as Data source 
        gvShowTasks.DataBind();//Binds the Grid
    }

 Run the solution and there you go .. whichever row you have selected , on click of delete button the same row will be deleted . you can also customise your delete query in the statement
  IMongoQuery query = Query.EQ("_id", bsonId);