System.Web.mvc.HtmlHelper does not contain a definition for EnumDropDownListFor

asp.net-mvc

Solution

You forgot to bring the extension method in scope inside the view. This `EnumDropDownListFor` method is defined in some static class inside a namespace, right?

namespace AppName.SomeNamespace
{
    public static class HtmlExtensions
    {
        public static MvcHtmlString EnumDropDownListFor<TModel, TEnum>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TEnum>> expression)
        {
            ...
        }
    }
}

You need to add this namespace inside the view in which you want to use this helper:

@using AppName.SomeNamespace
@model MyViewModel
...
@Html.EnumDropDownListFor(model => model.Code.Codes)

And to avoid adding this using clause to all your Razor views you could also add it to the `<namespaces>` section of your `~/Views/web.config` file:

<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="AppName.SomeNamespace" />
      </namespaces>
    </pages>
</system.web.webPages.razor>

Problem

I have been following this tutorial http://blogs.msdn.com/b/stuartleeks/archive/2010/05/21/asp-net-mvc-creating-a-dropdownlist-helper-for-enums.aspx but I run into the error "System.Web.Mvc.HtmlHelper does not contain a definition for EnumDropDownListFor". Model: ``` public enum Codes { IBC2012, IBC2009, IBC2006, FL2010, CBC2007 } public class Code { public int ID { get; set; } public int Active { get; set; } public string Description { get; set; } public string Edition { get; set; } public Codes Code { get; set; } } ``` Controller: ``` public static MvcHtmlString EnumDropDownListFor<TModel, TEnum>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TEnum>> expression) { ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData); IEnumerable<TEnum> values = Enum.GetValues(typeof(TEnum)).Cast<TEnum>(); IEnumerable<SelectListItem> items = values.Select(value => new SelectListItem { Text = value.ToString(), Value = value.ToString(), Selected = value.Equals(metadata.Model) }); return htmlHelper.DropDownListFor( expression, items ); } ``` HTML Helper: ``` @Html.EnumDropDownListFor(model => model.Code.Codes) ```

Original source