ASP.Net 4.5 new feature Model Binding

A nice feature with ASP.Net is the model binding, it reduced our code and effort to bind our well know controls like GridView, DataList, Repeater etc. So let’s see how we can bind our old controls in new and easy way. Let’s see how we bind the our grid before 4.5

  1. We write the code to get data from database
  2. Set the data source of control say GridView
  3. Finally call the DataBind() method

HTML Looks something like this:

<asp:GridView ID="gvCustomer" runat="server"
   AutoGenerateColumns="false">
   <Columns>
     <asp:BoundField DataField="CustomerID" HeaderText="ID" />
     <asp:BoundField DataField="CustomerName" HeaderText="Name" />
     <asp:BoundField DataField="Description" HeaderText="Description" />
  </Columns>
</asp:GridView>

and code behind

namespace MyProject.WebApp
{
  public class CustomerInfo
  {
    public IQueryable<Customer> GetCustomers()
    {
       MyDataContext  db = new MyDataContext();
       return db.Customers.Where(x=>x.IsActive == true);
    }
    publice void BindGrid()
    {
      gvCustomer.DataSource = GetCustomers();
      gvCustomer.DataBind();
    }
  }
}

Now let’s see the new feature in action, we don’t need to call a separate code behind method to bind the grid record, we will do it in Gridview itself, so what we need is to just add two more properties and set its values (ItemType and SelectMethod), see this:

<asp:GridView ID="gvCustomer" runat="server"
   AutoGenerateColumns="false"
   ItemType="MyProject.WebApp.CustomerInfo"
   SelectMethod=" GetCustomers">
   <Columns>
     <asp:BoundField DataField="CustomerID" HeaderText="ID" />
     <asp:BoundField DataField="CustomerName" HeaderText="Name" />
     <asp:BoundField DataField="Description" HeaderText="Description" />    
     <asp:TemplateField HeaderText="# of Customers">
         <ItemTemplate><%# Item.Customers.Count %></ItemTemplate>
     </asp:TemplateField>    
  </Columns>
</asp:GridView>

That’s it, no need of code behind to bind the grid.

Once you will set ItemType property, two new typed variables will be available in the scope of data-binding expressions: Item and BindItem. Because the variables are strongly typed now, you get the full benefits of the Visual Studio development experience. In above example we show “# of Customers” by using the item.Customers.Count without calling any extra method to get the total records and the most interesting thing, our best friend IntelliSense will be with us.

Now let's add a drop down to see records only for selected item in drop down, will we need code behind to search and bind the grid, no we don't need, let's see this

First add a label and drop down to the page:

<asp:Label runat="server" AssociatedControlID="ddlCity"
        Text="Select a city to show customers for: " />
<asp:DropDownList runat="server" ID="ddlCity"
        SelectMethod="GetCities" AppendDataBoundItems="true"
        DataTextField="CityName" DataValueField="CityID"
        AutoPostBack="true">
  <asp:ListItem Value="" Text="- All Cities -" />
</asp:DropDownList>

Code to get cities from database

public IQueryable<City> GetCities()
{
    MyDataContext  db = new MyDataContext();
    return db.Cities.Where(x=>x.IsActive == true);
 }

Have you noticed how we bind the drop down.

Now time to change the code to bind the GridView but we don't need to do any change in grid view binding, just we need to change the code to get the data i.e. GetCustomers method, so let's do this

public IQueryable<Customer> GetCustomers([Control("ddlCity")] int? cityID)
{
    MyDataContext  db = new MyDataContext();        
    IQueryable<Customer> query =  db.Customers.Where(x=>x.IsActive == true);

    if (ddlCity.HasValue && cityID > 0)
       query = query.Where(x => x.CityID == cityID);

    return query;          
}

Before completing let's add paging and sorting to the grid

<asp:GridView ID="gvCustomer" runat="server"
   AutoGenerateColumns="false"
   AllowPaging="true" 
   AllowSorting="true"
   ItemType="MyProject.WebApp.CustomerInfo"
   SelectMethod=" GetCustomers">
   <Columns>
     <asp:BoundField DataField="CustomerID" HeaderText="ID"   
           SortExpression="CustomerID" />
     <asp:BoundField DataField="CustomerName" HeaderText="Name" 
            SortExpression="CustomerName" />
     <asp:BoundField DataField="Description" HeaderText="Description" 
             SortExpression="Description" />    
     <asp:TemplateField HeaderText="# of Customers">
         <ItemTemplate><%# Item.Customers.Count %></ItemTemplate>
     </asp:TemplateField>    
  </Columns>
</asp:GridView>
Mike .Net
  • asp.net
By Mike .Net On 17 Jan, 13  Viewed: 3,200

Other blogs you may like

Readonly textbox postback issues and solutions

In many cases we need to use read only text box so user cannot edit the value but readonly textbox will lost its value after postback. Let’s say you have a read only text box to set date by using ajax calendar so after post back date will be lost, other case might be you are setting some value in... By Ali Adravi   On 24 Apr 2013  Viewed: 4,219

Call code behind method from JavaScript in asp.net

There are ways to call a web service method JavaScript, for more detail you can see [how to retrieve data from database using JavaScript in asp.net][1], but is there any way to call a normal method from JavaScript? And the answer is No; show how we can call a code behind method from JavaScript,... By Jonathan King   On 08 Apr 2013  Viewed: 12,445

Gridview paginated data with search and sort functionality in asp.net

Most of the times we need to use GridView control to show tabular data in our asp.net application. We simply write procedure to search the records and bind them with GridView and show 10 to 20 records per page. Have you ever thought that why you are fetching all the records and show only 10 to 20... By Ali Adravi   On 16 Feb 2013  Viewed: 8,386

Upload multiple image in multiple size with progress bar in asp.net

In asp.net there is not control to select multiple files and upload them once with progress bar, so we will use a small third party DLL to achieve this functionality. We will use Flajaxian FileUploader, you can download it from [http://www.flajaxian.com][1] We will create three different images... By Hamden   On 12 Jul 2012  Viewed: 6,546

Check/Uncheck all checkboxes in asp.net by javascript

I was searching for select/deselect all checkboxes code into a gridview. I found most of them only provide to select and deselet all the checkboxes if any of the checkbox is unselected into grid the main checkbox is not affecting. I further try to search some useful code but could not found any... By Ali Adravi   On 10 Jul 2012  Viewed: 5,376