Adding Extension Methods to the ASP.NET MVC 2 Strongly Typed Html Helpers
In my last post I talked about what I felt was missing in version 2 of the ASP.NET MVC framework. Specifically, I’m talking about the ability to map the “name” attributes of input control to properties of Request Models. I mentioned that it would be achievable via writing some extension methods, and here are some concrete examples.
Let’s start by writing extension methods for the “TextBoxFor” method. Essentially, I need methods where you can define the type of model that you want to map to. For example, the syntax I am aiming for would be like this:
This is an appropriate example for me to use, because typically on a Log-In page the “Password” property’s text will never be rendered on the screen. It will, however, be sent as part of a request when the page is posted. Therefore, it doesn’t fit to include this property as part of the View Model, but it does make sense to have it part of the Request Model.
To achieve this, I can create a new static class, and add some extension methods, as follows:
Let’s take a closer look at the third method – note how the signature allows you to specify the type of model:
If I then reference the namespace of my static class in my page, I can then use the extension methods, for example:![]()
If for example I did want to populate this field with a value when rendering the page, I can do so by specifying a value for the “value” attribute, i.e.:
I can then use my newly defined syntax to render a control which has the following HTML output:
<input id=”Password” name=”Password” type=”text” value=”" />
[...] MVC2 | In a previous post I talked about a neat way to submit forms via Ajax using jQuery. In another, more recent post I talked about some extension methods that you could add to the Html Helpers that will allow you to [...]