C# 向 MVC 项目添加自定义 HTML Helper

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18937128/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 13:38:34  来源:igfitidea点击:

Adding a custom HTML Helper to MVC Project

c#asp.net-mvcasp.net-mvc-3razorhtml-helper

提问by Code Ratchet

I've been browsing the web trying to find a good example/tutorial detailing how I can create and use my own custom HTML Helpers for my MVC 3 Razor application I found this one which is as follows

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

Adding your own HtmlHelper in ASP.NET MVC 3

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

I've created a class (trimmed it down a bit) as so

我已经创建了一个类(将其精简了一点)

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

     }
}

So far so good,

到现在为止还挺好,

Inside my controller I also added the reference

在我的控制器中,我还添加了引用

using System.Web.Mvc.Html;

Now inside my view i have the following

现在在我看来,我有以下几点

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

But I get the following error

但我收到以下错误

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

Could someone please tell me what im doing wrong here.

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

采纳答案by Ufuk Hac?o?ullar?

You should include the namespace in your view:

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

@using MyWebApp

Or you can import this namespace for all of the views from web.config.

或者,您可以为 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>

回答by Michael

I think an easier option would be to do the following: 1. Create a view as usual, place your helpers in that as usual with the mix of code and html as you like. 2. Move the view to the App_Code folder. 3. Get to your helps in all your views as so (Note that _MyHelpers is the name of the view in the App_Code folder):

我认为一个更简单的选择是执行以下操作: 1. 像往常一样创建一个视图,像往常一样将您的助手放入其中,并根据需要混合使用代码和 html。2. 将视图移动到 App_Code 文件夹。3. 在所有视图中获取帮助(请注意,_MyHelpers 是 App_Code 文件夹中视图的名称):

@_MyHelpers.JQMRadioTrueFalse("Voice Mail on your Home Phone?", "HomePhoneHasAnswerPhone", Model.TrueFalse, t.HomePhoneHasAnswerPhone)

This would be an example of a view in the App_Code folder that is accessed on any view as above:

这将是 App_Code 文件夹中的视图示例,可在上述任何视图上访问:

    @helper JQMRadioList(string Legend, string RadioListName, List<Fizz.DomainClasses.GenericClasses.GenericDropDownOption> options, bool Horizontal = false, string CurrentSelection = "")
    {
        <fieldset data-role="controlgroup" data-mini="true" data-theme="b" @((Horizontal) ? " data-type=\"horizontal\"" : "")>
            <legend>@Legend:</legend>
            @foreach (var li in options)
            {
                @JQMRadioListItem(RadioListName, li.TheValue, li.Text, CurrentSelection)
            }
        </fieldset>
    }