LA.NET [EN]

Dec 18

The MVC framework – refactoring the previous example

Posted in ASP.NET MVC      Comments Off on The MVC framework – refactoring the previous example

In the last post we’ve seen a really simple example of how to use the existing HtmlHelper methods for building a simple form. We’ve also seen how to validate those results and how to pass them for further processing. to achieve that, we used all “low-level” methods provided by the framework (ie, we’ve resorted to using the Request.Form collection to get all the submitted values from the form).

At the time, I said that there was an easier way to do the same with less code. In this post I’ll show you how! We’ll start by creating a new class for keeping the info introduced by the user. I’m calling it UserInfo:

public class UserInfo    {
        public String Name { get; set; }
        public String Password { get; set; }
        public String Sex { get; set; }
}

Now, the idea is to use the binding helpers to get an instance of type UserInfo automatically from the data that is submitted by the form which should be passed to our action method. Here’s the code for the HandleFormData:

public ActionResult HandleFormData([Bind(Prefix = "")]UserInfo user) {
   if (user == null ||
        String.IsNullOrEmpty(user.Name) ||
         user.Name.Length < 4) {
                ViewData.ModelState["name"].Errors.Add(
                      "name must have more than 4 chars");
                return View("Index");
    }
    return View("UntypedUserInfo",user);
}

If you compare this code with the previous example, you’ll notice that we’ve improved its readability while simultaneously reducing the number of lines of code. Lets take a deeper look at what’s going on here:

  • We’ve changed the HandleFormData method so that it receives an instance of UserInfo. The idea is to delegate the creation and initialization of that instance to the framework;
  • The BindAttribute instructs the framework to create and set the values of user from the values submitted by the form. The user of Prefix is necessary in this case. Without it, and by default, the framework would search for fields named user.name, user.sex, etc. (the  name user. comes from the name of the parameter). Another thing to keep in mind is that the framework will use the DefaultModelBinder class for initializing the class. I’ve already written about the binding model in the past, so now might be a good time to review that info. btw,Scott Gu has also a good post on how to use this feature.
  • Instead of using an untyped view,we’re now using type view so that we have compilation verification and intellisense when filling the info on our view. That’s why we’re forwarding the UserInfo to the View call.

I’m not sure on what you think about this, but I do like the end result. Yes, during the first time you might think that there’s simply too much magic going on here, but after understanding the basics and understanding what’s going on, it’s undeniable that we do really get better results (cleaner code which is really more expressive, right?).

We still need to change the view. The first thing to do is to change its codebehind file:

public partial class UntypedUserInfo: ViewPage<Data> {
}

And now, we can simply change the code on the aspx file to this:

<asp:Content ID="Content1"
         ContentPlaceHolderID="MainContent" runat="server">
         name: <%= Html.Encode( ViewData.Model.Name ) %><br />
         password: <%= Html.Encode(ViewData.Model.Password)%><br />
         sex: <%= Html.Encode(ViewData.Model.Sex)%><br />
</asp:Content>

Ok, to me this looks much  better. What do you think?

We’ll keep going on the next posts. Stay tunned!