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

标签 c# asp.net-mvc asp.net-mvc-3 razor html-helper

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

Adding your own HtmlHelper in ASP.NET MVC 3

我已经创建了一个类(将其略微缩减)

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"));
         }

     }
}

到目前为止一切顺利,

在我的 Controller 中我还添加了引用

using System.Web.Mvc.Html;

现在在我看来我有以下内容

@Html.StateDropDownList(x => x.State)

但是我得到以下错误

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

谁能告诉我我在这里做错了什么。

最佳答案

你应该在你的 View 中包含命名空间:

@using MyWebApp

或者您可以从 web.config 为所有 View 导入此命名空间。

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

关于c# - 将自定义 HTML Helper 添加到 MVC 项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18937128/

相关文章:

asp.net-mvc-3 - 面包屑- ASP.NET MVC3

c# - 合并多个列表,每个列表的可变长度为 "popping"个元素

c# - 带有嵌入式图像/css 的 ServiceStack Razor(自托管)

c# - 从回调中获取 oauth_verifier

javascript - 添加更改已保存的 Javascript 弹出窗口

asp.net-mvc-3 - 字段 ID 的 Razor 语法

c# - 编码结构数组指针的最佳方法

asp.net-mvc - 我可以共享相同的 View 以在 MVC3 中创建和编辑吗

asp.net-mvc - Kendo UI 调度程序 : Custom view and edit behavior

asp.net-mvc - 如何删除 mvc 中带有选定选项标签的下拉菜单的模型状态错误?