Model Binding in ASP.NET 4.5

In this article, we will explore a new feature introduced in ASP.NET 4.5 called Model Binding which displays data on our WebForms using the SelectMethod attribute of a data bound control. We will also see how to filter data using Value Provider Attribute Eg: [QueryString].

A couple of days ago, I had written an article on “Strong Typed Data Controls in ASP.NET 4.5” which demonstrated a new way of binding data to the data controls in ASP.NET 4.5. We will be using the same example in our demonstration. If you have not seen that article, I suggest you to go through it first.

Let’s start talking about Model Binding in ASP.NET 4.5. In earlier versions of ASP.NET web forms, we used different data sources to perform Insert, Select, Update and Delete operations. We especially used the Object Data Source to implement our own logic during these operations.

In ASP.NET 4.5 web forms, we can use Model Binding for our data bound controls. Now we can specify Insert, Select, Update and Delete methods directly in our data bound controls which can call the logic of the same from the code file of our web form or from other classes.

To see how this works, we will first create a new empty web application in Visual Studio 2012. Give some name to the empty web site. Now let’s add a new item in our web site which will be an “ADO.NET Entity Data Model” with the name “Northwind” as shown below –

addedf

This will bring up the “Entity Data Model Wizard”. Choose Generate from database and click on the Next Button. In this step, set a Connection to the Northwind database of your SQL Server. Once the connection is set, click on Next button. Now choose tbe Customers and Orders table and click on Finish button.

Now as our Data Model is ready, let’s add a new web form with the name “CustomersView”. Let’s design the form as shown below –

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="CustomersView.aspx.cs" Inherits="NorthwindModelBinding.CustomersView" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Repeater ID="rptCustomers" runat="server" ItemType="NorthwindModelBinding.Customer" SelectMethod="CustomersView_GetData">
            <HeaderTemplate>
                <h1 style="background-color:#000066;color:#FFFFFF">
                    Customers Data
                </h1>
            </HeaderTemplate>
            <ItemTemplate>
                <table border="1">
                    <tr>
                        <td><%#:Item.ContactName %></td>
                        <td><%#:Item.CompanyName %></td>
                        <td><%#:Item.City %></td>
                        <td><%#:Item.Country %></td>
                        <td><a href="OrdersView.aspx?CustomerID=<%#:Item.CustomerID%>">See All Orders</a></td>
                    </tr>
                </table>
            </ItemTemplate>
        </asp:Repeater>
    </div>
    </form>
</body>
</html>

  
Now write the following code in our code file as shown below –

public partial class CustomersView : System.Web.UI.Page
{
NorthwindEntities dataContext = new NorthwindEntities();
protected void Page_Load(object sender, EventArgs e)
{

}
public IEnumerable<NorthwindModelBinding.Customer> CustomersView_GetData()
{
   
    var query = from customers in dataContext.Customers
                select customers;
    return query.AsEnumerable();
}
}

Run your CustomersView WebForm and you will see an output similar to the following –

output1

In our code file, we have written a function “CustomersView_GetData” which returns the list of all the customers as IEnumerable<NorthwindModelBinding.Customer>. We have attached this method to our repeater control’s SelectMethod attribute as shown below –

selectmethod

We are also using a new feature of ASP.NET 4.5 which is Strongly Typed Data Controls. In our case, it is Repeater control as shown below –

stringtypedctl
Now let’s add a new web form with the name “OrdersView” and design the form like below –
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="OrdersView.aspx.cs" Inherits="NorthwindModelBinding.OrdersView" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
    <asp:GridView ID="GridView1" runat="server" BackColor="White" BorderColor="#999999" BorderStyle="None" BorderWidth="1px" CellPadding="3" GridLines="Vertical" ItemType="NorthwindModelBinding.Order" DataKeyNames="OrderID" SelectMethod="OrdersView_GetData" AutoGenerateColumns="true">
        <AlternatingRowStyle BackColor="#DCDCDC" />
        <FooterStyle BackColor="#CCCCCC" ForeColor="Black" />
        <HeaderStyle BackColor="#000084" Font-Bold="True" ForeColor="White" />
        <PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
        <RowStyle BackColor="#EEEEEE" ForeColor="Black" />
        <SelectedRowStyle BackColor="#008A8C" Font-Bold="True" ForeColor="White" />
        <SortedAscendingCellStyle BackColor="#F1F1F1" />
        <SortedAscendingHeaderStyle BackColor="#0000A9" />
        <SortedDescendingCellStyle BackColor="#CAC9C9" />
        <SortedDescendingHeaderStyle BackColor="#000065" />
        <Columns>
            <asp:BoundField DataField="OrderID" HeaderText="Order ID" />
            <asp:BoundField DataField="OrderDate" HeaderText="Order Date" />
            <asp:BoundField DataField="ShipCity" HeaderText="Order Ship City" />
        </Columns>
    </asp:GridView>
</div>
</form>
</body>
</html>

Now when we click on “See All Orders” from CustomersView page, it should show us all the Orders placed by that customer in OrdersView page. For this, we will have to create a Select Method in the code file of our OrdersView page as shown below –

public partial class OrdersView : System.Web.UI.Page
{
NorthwindEntities dataContext = new NorthwindEntities();
protected void Page_Load(object sender, EventArgs e)
{

}
public IQueryable<NorthwindModelBinding.Order> OrdersView_GetData([QueryString("CustomerID")]string CustomerID)
{
    var query = from orders in dataContext.Orders
                where orders.CustomerID == CustomerID
                select orders;
    return query;
}
}

  
If you observe, our OrdersView_GetData([QueryString(“CustomerID”)] string CustomerID) method takes a special value provider attribute [QueryString]. This is a new way in ASP.NET 4.5 Model Binding by which we can filter the data using value provider attributes. There are different value provider attributes as mentioned below –
  1. Controls on the page
  2. Query string values
  3. View data
  4. Session state
  5. Cookies
  6. Posted form data
  7. View state
  8. Custom value providers
We can use any one of these value provider attributes to filter the data. Now if you run CustomersView page and click the link “See All Orders”, on the OrdersView Page, you will see the Orders or a chosen customer as below –

clickseeorders
output2

That’s all. This is how the new Model Binding works in ASP.NET 4.5

Summary – In this article, we have explored a new feature introduced in ASP.NET 4.5 called Model Binding by displaying data on our web form using SelectMethod attribute of a data bound control. We have also seen how to filter the data using Value Provider Attribute that is QueryString.

The entire source code of this article can be downloaded over here https://github.com/devcurry/model-binding-winforms





1 comment:

Rashad Holder said...

You can now bind data controls directly to methods that provide select, insert, update and delete functionality.