ASP.NET 4.5 - New Model Binding Feature Keeps the Web Form and Model Separate

Posted by: Mahesh Sabnis , on 11/17/2011, in Category ASP.NET
Views: 181198
Abstract: The Model binding feature in ASP.NET 4.5 provides an exciting feature to developers to develop Webforms which can be independent from the Model.
Note: This article is written using Visual Studio 2011 Preview and ASP.NET 4.5. Since these are preview versions, this article may change in the future.

I have been working on ASP.NET and training developers since its early inception. Starting from its 1.x version, ASP.NET has attracted many developers through its new programming model and Web Controls, which has helped in developing Web Applications the easy way. In ASP.NET 2.0/3.5 we got a good provider model for security, navigation and APIs for health monitoring. In ASP.NET 4.0, features like routing etc were introduced. The ASP.NET technology has improved over these years and has  helped developers in creating Web Applications.

 


When developing Web Applications using Data-Models,  it is still necessary for us to write a lot of code, which sometimes can be complex. Although with the latest .NET Framework versions, we have been provided with mapping frameworks like the ADO.NET Entity Framework, objects mapped with database tables are still isolated from the ASP.NET DataBound controls. So for performing CRUD operations or pagination, we still need to write code. Implementing Master-Details forms can also become complex. The ASP.NET MVC framework provides a code-behind approach of application development where Data Model really drives our View (User Interface) using Controller, but that’s a different story. To understand the disadvantages of the Web Form model and how ASP.NET MVC solves the problem, read the article Difference Between ASP.NET WebForms and ASP.NET MVC

Model Binding Feature in ASP.NET 4.5

The Good News - In ASP.NET 4.5, we can adopt an approach using which the Model can be directly bound with the DataBound controls and CRUD and pagination operations can be implemented very effectively. It incorporates concepts from the ObjectDataSource control and from model binding in ASP.NET MVC. We will see this shortly. ASP.NET 4.5 is based upon .NET 4.5 and it gets installed once you install Visual Studio 2011 preview.  To get an overview of the various features of ASP.NET 4.5,  read this article.

Note: If you want to install Visual Studio 2011 preview, you can also use the Windows 8 Developer preview.

In this article I will be explaining a new ASP.NET 4.5 exciting feature called ‘Model Binding with Web Forms’. Up to previous versions, webforms for data-binding used to make use of the ‘Eval’ method. During runtime, calls to Eval makes use of reflection against the currently bound data object and reads value of the member with the given name in Eval method. (Read Why Eval is Evil). Once this value is read the result is displayed in HTML. Although this is easiest way of data-binding, it has limitations like checking the binding name during compilation time etc.

Update: Also check out the second part of this article ASP.NET 4.5: Filtering using Model Binding in ASP.NET Web Forms

In ASP.NET 4.5 the Model Binding has improved. We will be going through the complete model binding feature using the following steps:
  • Model binding with Web Forms.
  • Value Providers.
  • Filtering.
  • Performing Update Operations.
For this article I am using Sql Server 2008 R2 and a ‘Company’ database, with following Tables:

Department - DeptNo (int) Primary Key, Dname (varchar(50)),Location (varchar(50)).
Employee - EmpNo (int) Primary Key, EmpName (varchar(50)),Salary (int), DeptNo(int) Forwign Key.

Let’s get started.

Step 1: Open Visual Studio 2011 Developer Preview and create a new Web Application, make sure that the Framework version you select is .NET 4.5. Call this application ‘ASPNET45_ModelBinding’.

Step 2: In this project, add new folders and name them as Model and Department. In the Department folder, add two Web Forms (with master page). Name them as ‘Departments.aspx’ and ‘DepartmentDetails.aspx’.

Step 3: In the Model folder, add a new ADO.NET entity data model and name it as ‘CompanyEDMX.edmx’. In the Wizard, select Company Database and select Department and Employee table. After the completion of wizard, the below result will be displayed:

ASP.NET 4.5 Model Binding
Step 4: Open the Departments.aspx in the ‘Source’ view and add the Repeater control in it with the Department model bound to it as below.

asp.net 4.5 model binding 
The above code shows some modified databound features for DataBound controls in ASP.NET 4.5. The Department Model is assigned to the ‘ModelType’ property of the repeater. This property is available to all DataBound controls. This allows us to define the type of data that is bound to the control and also allows to bind properties of the Model inside the control. The above code defines ‘ItemTemplate’ inside the repeater control which refers to the ‘DepartmentDetails.aspx’ by passing DeptNo value using QueryString to it.


Step 5: Go to the Departments.aspx.cs code behind, and write the following code:

object context

The above code sets the datasource property for the repeater control.

Step 6: View the Departments.aspx inside the browser and the following result will be displayed:

clip_image002

In your OS, observe the lower right corner of the System Tray. Instead of the ASP.NET Development server, ASP.NET 4.5 uses IIS Express as shown below:

IIS Express

Step 7: In Step 4, we added the repeater control which has the ItemsTemplate and contains an <a href=””> to navigate to DepartmentDetails.aspx using a query string. This page is designed for displaying details of a particular Department. Open DepartmentDetails.aspx in the ‘Source’ view and add a DetailsView web UI databound control inside it. As explained Step 4, we need to assign the ModelType property of this control to ‘Department’ model.

All those who have used controls like DetailsView or FormView knows that these control are used for performing DML operations. Now to perform DML operations in earlier versions of ASP.NET i.e. from 2.0 to 4.0 we used to make use of ObjectDataProvider and this provider was usually configured using Get,Insert,Update and Delete methods form the source object. However the ASP.NET 4.5 DataBound controls e.g. GridView, FormView, DetailsView etc, exposes the following properties:
  • SelectMethod: Used to make call to a method which returns IEnumarable.
  • InsertMethod: Used to make call to a method which performs Insert operation.
  • UdateMethod: Used to make call to a method which performs Update operation.
  • DeleteMethod: Used to make call to a method which performs Delete operation.
Configure the DepartmentDetails.aspx as shown below:

details view binding asp.net 4.5

Step 8: Open the DepartmentDetails.aspx.cs and add the following code in it:

asp.net crud operations
 

Now carefully have a look at the above methods. None of these methods make use of any of the UI controls in the user interface. All these methods strictly work on Model objects and this feature drastically reduces additional coding. One more important fact is, if you observe the ‘GetDepartment()’ method, it has defined the ‘DeptNo’ input parameter with the QueryString Value provider. This automatically reads the DeptNo in the QueryString and displays the Department details inside the DetailsView.

Note: In previous versions of ASP.NET we could have done this using Request.QueryString[“DeptNo”]

Step 9: Now open Site.Master and add the following menu item:

<asp:MenuItem NavigateUrl="~/Department/Departments.aspx" Text="Departments"/>

Step 10: Make Default.aspx as a startup page and run the application. You will see the Default.aspx with Department and Employee menu. Once you click on ‘Department’ menu, Departments.aspx will be displayed. Now click on any Department and you will be transferred to ‘DepartmentDetails.aspx’ as below:

asp.net 4.5 query string

The QueryString has the DeptNo and based upon the value of the DeptNo, the DetailsView will display the  Department details. Here you can now test the Update and New (insert) functionality.

Check out the second part of this article ASP.NET 4.5: Filtering using Model Binding in ASP.NET Web Forms

Conclusion: The Model binding feature provides facility to the developers to develop Webforms which can be independent from the Model.

The entire source code of this article can be downloaded over here
Give me a +1 if you think it was a good article. Thanks!
Recommended Articles


Page copy protected against web site content infringement by Copyscape


User Feedback
Comment posted by iandt on Tuesday, November 29, 2011 4:38 AM
Ever heard of Rocky Lhotka and CSLA - his business object architecture that has been in existence for about 15 years ? Check out www.lhotka.net
Comment posted by Burton Taylor on Wednesday, November 30, 2011 5:45 AM
Really New Model Binding Feature is very valuable feature.


http://www.rapidsofttechnologies.com/asp.net-application-development.html
Comment posted by Praveen on Sunday, December 4, 2011 8:37 AM
Good post. I like it.
thanks
http://praveenbattula.blogspot.com/2011/12/aspnet-45-new-features.html
Comment posted by Bhaskar on Monday, January 23, 2012 4:40 AM
Great article about new features.

http://csharpektroncmssql.blogspot.com
Comment posted by safsdad on Saturday, February 11, 2012 11:38 PM
afdafsd asdfasdfsdf
Comment posted by anon on Saturday, August 4, 2012 11:58 AM
Is there a way to move the query,update and validation to a seperate class file or class files like creating a BLL.  I would like to be able to move the code out of the code-behind since to me it would be easier to read and maintain.  Thanks.


public void UpdateProduct(int productId)

{

    var product = _db.Products.Find(productId);

          

    TryUpdateModel(product);

          

    // Check whether there were any validation errors

    if (ModelState.IsValid)

    {

        _db.SaveChanges();

    }          
}
Comment posted by Eone James on Tuesday, September 4, 2012 12:46 AM
Your article is really wonderful and help me a lot in development. http://www.elantechnologies.com/services/web-apps/asp-net-ms-sql-development/
Comment posted by aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa on Thursday, November 15, 2012 8:58 AM
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

Post your comment
Name:  
E-mail: (Will not be displayed)
Comment:
Insert Cancel