将自定义HTML Helper添加到MVC项目

Cod*_*het 6 c# asp.net-mvc html-helper razor asp.net-mvc-3

我一直在浏览网页试图找到一个很好的示例/教程,详细说明如何为我的MVC 3 Razor应用程序创建和使用我自己的自定义HTML帮助程序我发现这个如下所示

在ASP.NET MVC 3中添加自己的HtmlHelper

我已经创建了一个类(稍微修剪了一下)

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Html;

namespace MyWebApp
{
    public static class ExtensionMethods
    {
         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"}

              };
              return html.DropDownListFor(expression, 
                       new SelectList(stateList, "key", "value"));
         }

     }
}
Run Code Online (Sandbox Code Playgroud)

到现在为止还挺好,

在我的控制器内部,我还添加了参考

using System.Web.Mvc.Html;
Run Code Online (Sandbox Code Playgroud)

现在在我的视图中我有以下内容

@Html.StateDropDownList(x => x.State)
Run Code Online (Sandbox Code Playgroud)

但是我收到以下错误

System.web.mvc.htmlhelper<system.collections.generic.list<Profile.ProfileImages>> does     not contain a definition for StateDropDownList and no extension method     StateDropDownList acception a first argument of type     system.web.mvc.htmlhelper<System.Collections.Generic.List<Profile.ProfileImages>> could be      found(Are you missing a using directive of an assembly reference?)
Run Code Online (Sandbox Code Playgroud)

有人可以告诉我这里我做错了什么.

Ufu*_*arı 16

您应该在视图中包含命名空间:

@using MyWebApp
Run Code Online (Sandbox Code Playgroud)

或者,您可以从web.config为所有视图导入此命名空间.

<system.web.webPages.razor>
  <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.Optimization" />
      <add namespace="System.Web.Routing" />
      <add namespace="MyWebApp" />
    </namespaces>
  </pages>
</system.web.webPages.razor>
Run Code Online (Sandbox Code Playgroud)