Adding your own HtmlHelper in ASP.NET MVC 3

47,937

Solution 1

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()

Solution 2

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>.

Share:
47,937

Related videos on Youtube

Chev
Author by

Chev

I'm a passionate developer and I love to learn. I also love to share my knowledge with others. Both of those are the primary reasons why I'm here on Stack Overflow :)

Updated on February 14, 2020

Comments

  • Chev
    Chev about 4 years

    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)

  • Chev
    Chev about 13 years
    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.
  • Chev
    Chev about 13 years
    This is closer, but DropDownListFor is not a property of html within the extension method context :/
  • Chev
    Chev about 13 years
    Bingo, I was missing using System.Web.Mvc.Html and for whatever reason it wouldn't automatically resolve. Thanks!
  • Kevin Le - Khnle
    Kevin Le - Khnle over 12 years
    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?
  • Andrew
    Andrew almost 12 years
    Add a using System.Web.Mvc.Html; to make the extension methods available.
  • Shaiju T
    Shaiju T over 8 years
    Where do you but your custom Html Helpers in your project ? as asked here ?
  • tklives
    tklives over 8 years
    @Khnle-Kevin - you need to include the model property it applies to: @Html.StateDropDownListFor(m => m.State)