ASP.NET 4.5 - New Model Binding Feature Keeps the Web Form and Model Separate
Posted by: Mahesh Sabnis
in Category ASP.NET
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.
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.
In ASP.NET 4.5 the Model Binding has improved. We will be going through the complete model binding feature using the following steps:
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:
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.
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:
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:
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:
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:
Step 8: Open the DepartmentDetails.aspx.cs and add the following code in it:
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:
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.
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
This article has been editorially reviewed by Suprotim Agarwal.
C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.
We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).
Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.
Click here to Explore the Table of Contents or Download Sample Chapters!
Was this article worth reading? Share it with fellow developers too. Thanks!
Mahesh Sabnis is a DotNetCurry author and a Microsoft MVP having over two decades of experience in IT education and development. He is a Microsoft Certified Trainer (MCT) since 2005 and has conducted various Corporate Training programs for .NET Technologies (all versions), and Front-end technologies like Angular and React. Follow him on twitter @maheshdotnet
or connect with him on LinkedIn