April 22, 2013

ASP.NET Web Forms Model Binding – My Favorite ASP.NET 4.5 Feature

I have been working on this blog posting for over 2-3 weeks, by far one of the longest writes of any posting that I’ve done in the past. The reason for this is that I’m writing about a concept that you should already be aware of which is the inclusion of Model Binding Support for Web Forms in ASP.NET 4.5. You can find a number of resources out there that talk about this, including this amazing tutorial series. So why do I feel the need to spend so much of my time writing about this feature? Well read on to find out!

Purpose of This Article

Almost a month-and-a-half ago I was asked what my favorite .NET 4.5/Visual Studio 2012 feature was.  It took a while to think about the possibilities with so many new features ASP.NET Model Binding for Web Forms was my top choice.  I landed on this topic due to its importance for developers and it is the one feature that I personally have come to love and is one of the key reasons that I’m moving my projects to ASP.NET 4.5 as the amount of developer time that is saved is impressive. Initially when I set out to write this posting it was to be a full-out tutorial walk through about how to use Model Binding in your applications. The direction for this changed dramatically just as I was getting ready to put together this posting after I stumbled across the above linked tutorial series as there was no way that I could possibly compete with such a well thought out tutorial series with a single blog posting.

As such, I’ve decided to take a different approach and tackle the “why” side of the coin, why it is such an amazing feature, what you need to know to use Model Binding, and why if you are a Web Forms developer you should be paying attention to this feature and using it in your projects. By doing this I feel that I can complement this material that Tom FitzMacken created..

What is Model Binding?

Those that are familiar with the ASP.NET MVC way of doing things should be familiar with Model Binding as it is a key foundation of how ASP.NET MVC works. For those not familiar it is most easily explained as a process that prevents you from writing a bunch of boiler plate code to take an object from your Business Tier and bind/map it to controls, grids, and other options in the UI of your applications. A key process that becomes important with model binding is the usage of Data Annotations.

Understanding Data Annotations

The key to properly understanding the power of ASP.NET Model binding is to first understand the purpose and function of Data Annotations. Initially added to the .NET framework in 3.5 for ASP.NET MVC’s Dynamic Data process, Data Annotations allow developers to use attributes to describe their objects in a declarative manner specifying the format and other metadata for their objects. For example a few helpful attribute definitions might look like the following:

[CreditCard(ErrorMessage=”Must be a valid credit card”)]
can be added to a string to denote and validate that the value stored within is a valid credit card.
[Display(Name=”My Custom Name”)]
can be applied to any class to ensure that when displayed the value “My Custom Name” is used. An example of a few properties from a Person class might look like the following :
[Display(Name=”First Name”)]
[Required(ErrorMessage=”You must supply a first name”)]
public string FirstName {get; set;}
[Display(Name=”Your Birthday”)]
public DateTime Birthday {get; set;}
[Display(Name=”Favorite Number (1-100)”)]
public int FavoriteNumber {get; set;}

From these attributes we can see that the First Name when displayed to the user should be using the longer “First Name” value and that the user must supply one. We also see that we need their birthday, and lastly we see that we require a single “Favorite Number” that must be between the values of 1 and 100. Now, this is great, but why is this so important?

Well as part of Model Binding in ASP.NET Web Forms 4.5 these annotations are fully recognized by the Web Forms controls that you have been using already, GridView, Repeater, FormView, etc. A new property exists on these controls called “ItemType” which allows you to specify the item type that is one of the key’s to harnessing the new powers of Model Binding. From there though the attributes are pulled out and used automatically for you. For example if you allow editing within a GridView all of the needed RequiredFieldValidators, RangeValidators, CompareValidators and such will automatically be generated for you keeping your interface proper to the intended data types.

Item Type Property & New Binding Process

The ItemType property is a simple step that is needed and shown in almost all of the tutorials but the real value of it isn't necessarily known until you start to look some of the other benefits that you get in addition to the items from the previous section.

One great example of the other benefits is around its ability to help in custom ItemTemplates. We all have written something like <%# Eval(“MyColumn”) %> or similar for binding items item templates in Grids or Repeaters. We all have also surely mis-typed a column name to only find out about it later when we debug our applications. What a pain, right?

Well this is where the Item Type properly will become your best friend, with this property specified you can bind to your object using something similar to the following: <%# Item.MyColumn %>. This might not look like anything big, but take a second to look at this, and try it on a Web Form. Visual Studio with the ItemType attribute properly set will provide full IntelliSense support for the Item. Syntax, this means that you will not have those situations where you are typing in a property name incorrectly. Even more so, renaming a properly in your code and using the refactoring tools to re-name items it will catch these items as well, reducing your time to test name changes.

Model Binding Value Providers

The last key “feature set” that I want to call attention to are the “Value Providers” that are helpful for not only usage with data bound controls that can use the new Model Binding syntax, but even for other methods. There are a number of value providers, that allow you to use attributes to setup parameters to methods, this allows you to simplify things such as data binding and auto-filtering. The following value providers are part of ASP.NET 4.5.

  • Control – Allows you to automatically pass in a control to a method
  • QueryString – Allows a querystring value to be automatically parsed and passed example public myMethod([QueryString]int? itemId)
  • Session – allows you to automatically grab values from SessionState
  • Cookie – Allows you to automatically grab values from a HTTP cookie
  • Form – Allows you to automatically grab values from the posted form
  • ViewState – Allows you to automatically grab values from views

What is the Total Value?

If you follow through the above listed highlights and then have a look at the tutorial series that I referenced above you should see where some of the key benefits come from with regards to Model binding. The main benefit being the ability to streamline your development processes and limit the amount of boilerplate code that you write and get you focused on building out the complex part of your application so you can be truly productive.

I know many people might start to look at some of this like they looked at things such as the “SqlDataSource” and other objects from the early .NET days. Where you might think that these controls and language features are great for rapid prototyping, but don’t necessarily scale well. The important thing to remember with Model Binding is if you combine this with iQueryable and Entity Framework or similar you actually get truly amazing performance with a simple developer interactions.

I will try to incorporate more detailed examples in future blog postings on the topic.

tags: ASP.NET, DNN Development, .NET 4.5
comments powered by Disqus

Content provided in this blog is provided "AS-IS" and the information should be used at your own discretion.  The thoughts and opinions expressed are the personal thoughts of Mitchel Sellers and do not reflect the opinions of his employer.

Content Copyright

Content in this blog is copyright protected.  Re-publishing on other websites is allowed as long as proper credit and backlink to the article is provided.  Any other re-publishing or distribution of this content is prohibited without written permission from Mitchel Sellers.