Adding your own HtmlHelper in ASP.NET MVC 3

Related searches

I am new to MVC and I am trying to create my own extension method so that I can add onto the html helpers that are available in my razor views. Html.DropDownListFor() lets you create a drop down list for any propery on your model. I would like to create a helper called Html.StateDropDownListFor() that does the exact same thing, except loads the drop down with all 50 US states. This way I don't have to create a SelectList for every single state drop down that I create. What is the easiest way to do this? Right now I have this:

public static class ExtensionMethods
{
    public static MvcHtmlString StateDropDownList(this HtmlHelper html)
    {
        // ???
    }
}

Am I even close? I don't want to rebuild a whole text box helper, I just want to create a helper that utilizes the existing text box helper but does the SelectList for me. That way in my views I could just do Html.StateDropDownList(x => x.State)

To use the custom helper method in your Razor views you will need to bring it into scope. There are two possible ways to do this:

  1. Add a @using SomeNamespace in the top of your view with the namespace where the static class containing the helper is defined
  2. In ~/Views/web.config, add:

    <system.web.webPages.razor>
        <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
            <pages pageBaseType="System.Web.Mvc.WebViewPage">
                <namespaces>
                    <add namespace="System.Web.Mvc" />
                    <add namespace="System.Web.Mvc.Ajax" />
                    <add namespace="System.Web.Mvc.Html" />
                    <add namespace="System.Web.Routing" />
                    <add namespace="SomeNamspace" />
                </namespaces>
            </pages>
        </system.web.webPages.razor>
    

Once the custom helper is brought into scope in the view, Intellisense should be able to pick it and you could use it:

@Html.StateDropDownList()

Now you helper method needs to do something useful. You could either call existing helpers:

public static class ExtensionMethods
{
    public static MvcHtmlString StateDropDownList(this HtmlHelper html)
    {
        return html.TextBox("foo")
    }
}

or return some custom data:

public static class ExtensionMethods
{
    public static MvcHtmlString StateDropDownList(this HtmlHelper html)
    {
        return MvcHtmlString.Create("Hello world");
    }
}

If you have a strongly typed view and you wanted to use an expression:

using System.Web.Mvc;
using System.Web.Mvc.Html;

public static class ExtensionMethods
{
    public static MvcHtmlString StateDropDownList(
        this HtmlHelper<MyViewModel> html
    )
    {
        var stateList = new SelectList(new[]
        {
            new { Key = "Alabama", Value = "Alabama" },
            new { Key = "Idaho", Value = "Idaho" },
            new { Key = "California", Value = "California" }
        }, "Key", "Value");
        return Html.DropDownListFor(
            x => x.State, stateList, "-- Select a state --"
        );
    }
}

and then:

@Html.StateDropDownList()

Creating Custom HTML Helpers (C#), Next, I describe two methods of creating custom HTML Helpers: I For example, you can use HTML Helpers to render standard HTML tags like NET MVC framework includes the following set of standard HTML The class in Listing 3 adds an extension method to the HtmlHelper class named Label() . Extension methods enable you to add new methods to an existing class. When creating an HTML Helper method, you add new methods to the HtmlHelper class represented by a view's Html property. The class in Listing 3 adds an extension method to the HtmlHelper class named Label(). There are a couple of things that you should notice about this class.

using System.Web.Mvc.Html;
public static MvcHtmlString StateDropDownList<TModel, TValue>( this HtmlHelper<TModel> html,
    Expression<Func<TModel, TValue>> expression ) {
        return html.DropDownListFor( expression, _stateList );
}

Would work. _stateList being an IEnumerable<SelectListItem>.

Create a Custom HTML Helper in ASP.NET MVC Using Razor, Creating a custom HTML helper. When you have a specific use case that isn't covered by the default HTML helpers, you can create your own� ASP.NET MVC provides many built-in HTML helper methods that we can directly use in a view. The MVC framework also provides the facility to create Custom HTML Helpers in ASP.NET MVC application. Once you create your custom HTML helper method then you can reuse it many times.

(Posted a solution on behalf of the question author, to move it to the answer section).

Here's the answer!

Here is the completed extension method in case anyone else ever has a use for it.

    public static MvcHtmlString StateDropDownListFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression)
    {
        Dictionary<string, string> stateList = new Dictionary<string, string>()
        {
            {"AL"," Alabama"},
            {"AK"," Alaska"},
            {"AZ"," Arizona"},
            {"AR"," Arkansas"},
            {"CA"," California"},
            {"CO"," Colorado"},
            {"CT"," Connecticut"},
            {"DE"," Delaware"},
            {"FL"," Florida"},
            {"GA"," Georgia"},
            {"HI"," Hawaii"},
            {"ID"," Idaho"},
            {"IL"," Illinois"},
            {"IN"," Indiana"},
            {"IA"," Iowa"},
            {"KS"," Kansas"},
            {"KY"," Kentucky"},
            {"LA"," Louisiana"},
            {"ME"," Maine"},
            {"MD"," Maryland"},
            {"MA"," Massachusetts"},
            {"MI"," Michigan"},
            {"MN"," Minnesota"},
            {"MS"," Mississippi"},
            {"MO"," Missouri"},
            {"MT"," Montana"},
            {"NE"," Nebraska"},
            {"NV"," Nevada"},
            {"NH"," New Hampshire"},
            {"NJ"," New Jersey"},
            {"NM"," New Mexico"},
            {"NY"," New York"},
            {"NC"," North Carolina"},
            {"ND"," North Dakota"},
            {"OH"," Ohio"},
            {"OK"," Oklahoma"},
            {"OR"," Oregon"},
            {"PA"," Pennsylvania"},
            {"RI"," Rhode Island"},
            {"SC"," South Carolina"},
            {"SD"," South Dakota"},
            {"TN"," Tennessee"},
            {"TX"," Texas"},
            {"UT"," Utah"},
            {"VT"," Vermont"},
            {"VA"," Virginia"},
            {"WA"," Washington"},
            {"WV"," West Virginia"},
            {"WI"," Wisconsin"},
            {"WY"," Wyoming"},
            {"AS"," American Samoa"},
            {"DC"," District of Columbia"},
            {"FM"," Federated States of Micronesia"},
            {"MH"," Marshall Islands"},
            {"MP"," Northern Mariana Islands"},
            {"PW"," Palau"},
            {"PR"," Puerto Rico"},
            {"VI"," Virgin Islands"},
            {"GU"," Guam"}
        };
        return html.DropDownListFor(expression, new SelectList(stateList, "key", "value"));
    }

I modified the code above to use a dictionary for state abbreviations.

Just don't forget to reference System.Web.Mvc.Html at the top of your extension method class like I forgot to.

Custom HTML Helper In ASP.NET MVC, Next Recommended Article Creating Custom HTML Helpers in ASP.Net MVC 5� In the above page we created label, textbox, and checkbox using the html helper and the following result is visible when we run this code, Custom Helper Sometime inbuilt helpers don’t provide the desire result, but ASP.NET MVC provides the concept of custom helper using what we can create as an html helper according our requirement.

Custom HTML Helpers In MVC, Next Recommended Article Creating Custom HTML Helpers in ASP.Net MVC 5� HTML Helpers. Here, you will learn what HTML helpers are and how to use them in the razor view. The HtmlHelper class renders HTML controls in the razor view. It binds the model object to HTML controls to display the value of model properties into those controls and also assigns the value of the controls to the model properties while submitting a web form.

Inline and Custom HTML Helpers in ASP.NET MVC, 3. Custom HTML Helpers. In this article, we will learn how to create inline @ helper syntax is used for creating reusable inline helper methods. ASP.NET MVC 3 is a framework for developing highly testable and maintainable Web applications by leveraging the Model-View-Controller (MVC) pattern. The framework encourages developers to maintain a clear separation of concerns among the responsibilities of the application – the UI logic using the view, user-input handling using the

Creating your own helper has the advantage that the page is cleaner and more readable. An additional benefit is that we can now write a unit test for this particular HTML helper. For example, imagine a website that allows a user to upload an image of their bike trip. If the user clicks on the image, a file selector popup shows up. This popup

Comments
  • I think you misunderstand. I know how to use the extension method in my view. I just don't know what to do in the extension method to utilize the existing TextBoxFor helper in order to create my own helper, built off the existing helper.
  • Bingo, I was missing using System.Web.Mvc.Html and for whatever reason it wouldn't automatically resolve. Thanks!
  • I get a run-time error in HTML page because it is called with no argument, but the definition includes 1 which is this HtmlHelper helper. Do you know why?
  • Where do you but your custom Html Helpers in your project ? as asked here ?
  • @Khnle-Kevin - you need to include the model property it applies to: @Html.StateDropDownListFor(m => m.State)
  • This is closer, but DropDownListFor is not a property of html within the extension method context :/
  • Add a using System.Web.Mvc.Html; to make the extension methods available.