Adding a custom HTML Helper to MVC Project

怎甘沉沦 提交于 2019-11-30 07:30:39
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.

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

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

@_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:

    @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>
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!