Model Binding with Strongly Typed HTML Helpers in ASP.NET MVC

Here are some example of how to perform model binding in ASP.NET MVC with strongly typed Html Helpers.


In this scenario, we have a simple controller that has rendered a view and will be saving information form said view.

public class ThingController : Controller  
    public ActionResult Edit(int id)
        // create a view model that would contain all sorts of things
        // required by our view to render properly
        var product = FindProductById(id);
        var model = new EditThingModel() 
            Product = product
            // other stuff goes here
        return View("edit", model);

The form we are building uses strongly-type HTML helpers.

@model EditThingModel

@using(Html.BeginForm("save", "thing")) {

   @Html.TextBoxFor(x =>x.Product.Name)
   <input type="submit" />


Under the covers, the strongly typed Html Helper will render the TextBox with the name Product.Name.


This annotation specifies the object and property that are being rendered and are used for model binding complex objects.


The DefaultModelBinder is capable of handling simple types, complex types, and collections. For a more complete overview of Model Binding, I suggest reading The Features and Foibles of ASP.NET Model Binding.

Automatic Binding to Complex Object

If the name of your argument happens to match the name of the prefix generated by your helper, you don't need to worry. In this example our Html Helper added a prefix of Product. Since our argument is named product the DefaultModelBinder will automatically bind these values to our object.


Binding with a Different Prefix

Suppose we have a different named argument in our Controller, such as p. This presents a problem since it does not match our prefix Product. We will need to specify the correct prefix. This is where the Bind attribute comes into place.

You can use the Bind Attribute to specify the prefix that should be use to bind your complex object. The Bind attribute can also be used to include/exclude values from binding.

As shown, the argument p uses the Bind attribute to specify the correct prefix of Product. All values matching the specified prefix will then be bound to our object.


Binding Simple Types

Lastly, what if you just want to bind to simple types? You can again use the Bind attribute to help you out, however there is a twist. Now when specifying the prefix, you will need to specify both the prefix and property name that you wish to apply to that argument. In this case, we want to bind the argument name we will have to specify the prefix Product.Name which matches the output from our Html Helper.

public ActionResult Save([Bind(Prefix="Product.Name")]string name)  
     // DO STUFF
comments powered by Disqus