BT

Facilitating the Spread of Knowledge and Innovation in Professional Software Development

Write for InfoQ

Topics

Choose your language

InfoQ Homepage News ASP.NET MVC Model Binding

ASP.NET MVC Model Binding

This item in japanese

Model Binding is a feature that simplifies controller actions by using the request data to create strongly typed objects. Jess Chadwick takes a deep dive into this feature in an MSDN article and explores complex scenarios, as well as creating custom model binders when the default model binder is not enough. 

What is ASP.NET MVC Model Binding? It enables code like this - 

public ActionResult Create()
{

var product = new Product() {

AvailabilityDate = DateTime.Parse(Request["availabilityDate"]),
CategoryId = Int32.Parse(Request["categoryId"]),
Description = Request["description"],
Kind = (ProductKind)Enum.Parse(typeof(ProductKind),
Request["kind"]),
Name = Request["name"],
UnitPrice = Decimal.Parse(Request["unitPrice"]),
UnitsInStock = Int32.Parse(Request["unitsInStock"])

}

};

to be replaced with this - 

public ActionResult Create(Product product)
{
// ...
}

ASP.NET automatically maps the query string parameter names with the property names in the strongly typed object. This also supports JSON post values. Model binding works even in advanced cases such as collections and nested objects, although with collections you have to be careful about the syntax (which involves using indexers to represent items in the collection). 

You still might want to extend the model binding frameworks with your own custom model binder in some cases. A common example is binding to interfaces and abstract classes, which needs strong coupling with the underlying business model (since the binder need to choose a particular implementation at runtime based on the request data). Jess's article shows how this can be achieved by just inheriting the DefaultBindingProvider and overriding behavior that’s necessary. For an example on how to unit test your custom model binders, refer Scott Hanselmann's article Splitting DateTime - Unit Testing ASP.NET MVC Model Binders

Rate this Article

Adoption
Style

BT