SSW Foursquare

Do you use Model Binding instead of FormCollection?

Last updated by Brook Jeynes [SSW] 9 months ago.See history

Model binding in the ASP.NET MVC framework is simple. Your action methods need data, and the incoming HTTP request carries the data you need. The catch is that the data is embedded into POST-ed form values, and possibly the URL itself. Enter the DefaultModelBinder, which can magically convert form values and route data into objects.

Model binders allow your controller code to remain cleanly separated from the dirtiness of interrogating the request and its associated environment.

public ActionResult Create(FormCollection values)
{
    Recipe recipe = new Recipe();
    recipe.Name = values["Name"];      
            
    // ...
            
    return View();
}

Figure: Bad example – Manually reading form values and assigning them to properties is tedious boiler-plate code!

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(Recipe newRecipe)
{            
    // ...
    
    return View();
}

Figure: Good example – Using MVC’s model binding allows you to work with an automatically-populated object instead

We open source. Powered by GitHub