Mar 11

As you might expect (from the title), this is another post on the MVC controls series. Today we’ll be looking at the MvcInputControl class which is responsible for rendering the text input controls. As you might expect, this class expands the MvcControl class and it exposes only one constructor which receives the type of text input you want to generate (as we’ll see, the current release supports only simple, password and hidden text controls). This parameter ends up initializing the InputType property. The class does exposes another property, Name, which is used in the same way that you saw in the Label post.

Besides these two properties, the class is also responsible for rendering the HTML. it does that by overriding the Render method and using it to output the corresponding HTML INPUT element. The rendering process involves:

  • going through all the attributes and adding them to the current element that is going to be outputted;
  • add the correct INPUT type by checking the InputType property;
  • add the name and id attributes. These are set to the Name property if you don’t explicitly pass a value to those attributes on the markup;
  • the INPUT value’s is added to the output, whenever possible. The algorithm used is based on the one presented for the Label control. Basically, whenever it can, it gets the value from the  view data dictionary that gets passed in.

And that’s it. Currently, this wrapper doesn’t do anything else. Whenever you need a text control,you must use one of the derived classes: TextBox,Hidden or Password. This classes are only there to introduce a default constructor which is responsible for extending the MvcInputControl class and for passing the correct type to the base constructor. For instance, here’s what you have for the TextBox control:

public class TextBox : MvcInputControl {
       public TextBox() :
           base("text") {

If we reuse the previous example, then we the following snippet will produce a textbox with its value set to whatever exists in the view data dictionary with that key:

<mvc:TextBox runat=”server” name=”Message” />

And here’s the HTML I’m getting on my browser:

<input name="message" id="message" type="text" name="message" id="message" value="hi there! This is aa label" />

And that’s it for today…more about MVC on the next posts.

2 comments so far

  1. Colin Gemmell
    1:55 pm - 3-11-2009

    This is possibly a silly question but why do we need MVC Controls? To me this is a move back to web form controls with all the hidden html (which often was terrible) that comes with it. What I love about ASP.NET MVC is having full control of my html again and making it readable. I could just about accept the argument that you want to reuse html but that is what user controls and Html Helpers are for.

  2. luisabreu
    3:01 pm - 3-11-2009

    Well, it might be a question of taste, but I do prefer to see markup in my code than embedded code delimited by all over the place…