The MVC platform: wrapping up the textbox helper

After a long pause, it’s time to go back to the MVC series. Today I’ll wrap up with a last post which mentions a scenario I’ve missed when I talked about the automatic hooking of properties to form fields. In a previous post, we’ve seen how easy it is to associate fields to simple properties of an object. Today, we’re going to see how easy it is to bind complex properties (ie, properties which are classes themselves). We’ll reuse the class presented in one of the previous posts and we’ll change it so that it has a complex property:

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

As you can see, this is really a contrived example, but it will do for now since my only objective is to show you how to hook up the complex property to the control. So, the big question is what must you do so that the MoreInfo subproperty is automatically filled with the control’s value? Easy: just set the name parameter of the helper to the “complete” name of the property. Here’s the code I’ve added to the existing HTML code presented in an earlier example:

<label for="AuxiliaryInformation.MoreInfo">Auxiliary info:</label>

And that’s it. If you have a method similar to the one presented in this post, you’ll notice that the AuxiliaryInformation property is correctly filled with the value passed from the HTML input you’ve added to the page. I’ve run some tests and you’ll be happy to know that the property is correctly filled even when you have readonly complex properties (that is, even if AuxiliaryInformation is read-only, you’ll be able to pass a value to the  MoreInfo “sub-property”).

Do notice that you need to pass the same value to the for attribute of the HTML label so that it is associated with the generated textbox. And that it’s it for this post. Keep tuned!


~ by Luis Abreu on January 26, 2009.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: