May 20, 2013

Model Binding Feature in Asp.Net 4.5

In Asp.Net 4.5, many new features has been shipped. Here I discuss about Model Binding feature which is creating their own space among others.

Data bound controls are the major part of typical web form applications and we spend a lot of time in writing code related to different events of that control.

The new functionality makes task easier so that you as a developer can focus on data and entities. To better understand the code let me first explain the scenario.

We want to display all the records of above table in GridView control which  also supports Paging and Sorting functionality. How would we do this?

OLDER WAY

To display data in Gridview, we required markup like that:

<asp:GridView ID="EmployeeGridView" runat="server" AllowSorting="true"
OnSorting="EmployeeGridView_Sorting">
</asp:GridView>


To populate GridView from code-behind, we required code as:

var dataContext = new DatabaseDataContext(Classes.GetConnectionString);
var employeeList = (from e in dataContext.Employees
                   select e).ToList();

if (employeeList.Count > 0) 
{
   EmployeeGridView.DataSource = employeeList;
   EmployeeGridView.DataBind();
}


And we need to create separate events of GridView, in order to use Paging or Sotring like,

protected void EmployeeGridView_Sorting(object sender, GridViewSortEventArgs e)
{
    var dataContext = new DatabaseDataContext(Classes.GetConnectionString);
    var employeeList = (from e in dataContext.Employees
                   select e).ToList();

    if (employeeList.Count > 0) 
    {
       EmployeeGridView.DataSource = employeeList;
       EmployeeGridView.DataBind();
    }
}



NEW WAY

Asp.Net 4.5 introduce a new feature called Model Binding which take advantage of System.Linq.IQueryable type.

public IQueryable<Employee> GetEmployeesList()
{
    var dataContext = new DatabaseDataContext(Classes.GetConnectionString);
    IQueryable<Employees> employeeList = (from e in dataContext.Employees
                   select e).ToList();
    return employeeList;
}


Now write a Gridview control markup as:

<asp:GridView ID="EmployeeGridView" runat="server" 
    ItemType="DataBindingSample.Employees" SelectMethod="GetEmployees">
</asp;GridView>

Here:
  • ItemType refers to table name define within IQueryable tag
  • SelectMethod refers to name of method

Now run the application, it will show you all records from table "Employee" in GridView. If you want to add Paging or Sorting functionality, go ahead just allow both functionality in GridView markup and rest of things will be handle by Model Binding itself.

It would change the way how data controls were generally managed in web form applications. Stay tuned!