You can’t help but notice the impact System.ComponentModel and System.ComponentModel.DataAnnotations have had on ASP.NET MVC 2. The DefaultModelBinder now supports all the validation attributes when doing model binding. The new template helpers in ASP.NET MVC 2, Html.DisplayFor, Html.EditorFor, Html.LabelFor, etc. use various attributes that affect the display of complex objects and their individual properties. And, as I will mention here quickly, you can also use the DefaultValue Attribute in System.ComponentModel to specify default values for action parameters.
[DefaultValue] Attribute in ASP.NET MVC 2
You may have optional parameters on your ASP.NET MVC 2 Actions that you want to set to a default value during model binding. A good example of this may be when paging a list of customers in your application where the pageSize is optional and defaults to 25. One can pull this off in many ways we won’t discuss here, but one of the simplest ways is to decorate the pageSize parameter in the action method with [DefaultValue(25)]. Below is an example:
public class CustomersController : Controller
{
private readonly ICustomerDAO _dao;
public CustomersController(ICustomerDAO dao)
{
_dao = dao;
}
public ActionResult Index(int itemIndex, [DefaultValue(25)]int pageSize)
{
var customers = _dao.Skip(itemIndex - 1).Take(pageSize);
return View(customers);
}
}
If pageSize is not provided during model binding, it will be set to the value of 25 as specified in the DefaultValue Attribute. If it is specified, say as a querystring parameter in the URL, pageSize will of course take on the value provided in the URL.
C# 4 Default Values
If you are developing your ASP.NET MVC 2 web application using C# 4, you can skip the use of the DefaultValue Attribute and just assign the default value to pageSize. Specifying default values in C# 4 works along with other new features in C# 4 concerning Named and Optional Parameters.
public class CustomersController : Controller
{
private readonly ICustomerDAO _dao;
public CustomersController(ICustomerDAO dao)
{
_dao = dao;
}
public ActionResult Index(int itemIndex, int pageSize = 25)
{
var customers = _dao.Skip(itemIndex - 1).Take(pageSize);
return View(customers);
}
}
Conclusion
I am really looking forward to ASP.NET MVC 2 being included with Visual Studio 2010 when it is released around April 12, 2010. When that happens I believe a number of developers will start to learn and appreciate the ASP.NET MVC Framework. Check out a list of ASP.NET MVC 2 Tutorials I wrote quite some time ago.
Hope this helps.

Comments