We know that the ASP.NET MVC Framework is smart enough to
translate our FirstName TextBox into the firstName string parameter in our
controller action. This is some very powerful stuff that has been added into
the framework. This gets better though because the framework also allows for
full object mapping using model binders. This will take the individual
parameters and construct a full data model object based on the data.
In our example, we have the values required for a User
object. Since this object does not yet exist, we will need to create it. So to
start off this section of the article, we will create a basic class which we
will use to model the data.
Listing 6: Simple User data model object
public ActionResult DisplayUserData3(User user)
ViewData["FirstName"] = user.FirstName;
ViewData["MiddleName"] = user.MiddleName;
ViewData["LastName"] = user.LastName;
Using the model binder allows us to skip the step of
assigning the parameters to our data object. Most of the time we want to work
with more advanced objects than the primitive types often passed by the simple
form controls. Also, the User object is very nice to just obtain. If our user
object had more properties associated with it, we would be quite glad to have
the one parameter as opposed to having half a dozen parameters to deal with in
our controller action.
It is possible to create custom model binders to deal with
more complex situations than this one. In fact one of the most powerful assets
available to the savvy ASP.NET MVC developer is the ability to customize the
framework to suit specific needs. There are interfaces to implement and base
classes to inherit which allow for a great deal of customization. This comes in
handy when using inversion of control to invert the dependencies of your code,
which is very common when working with controllers in ASP.NET MVC.
Once we execute the code using this action in our HTML form,
we receive the same result we did before. We obtain the same view of the data,
which shows us that these methods are fairly interchangeable. There are
circumstances for each.
Figure 9: Display view with model bound data