【问题标题】:Adding HtmlHelper NameSpace in Web.Config does not work在 Web.Config 中添加 HtmlHelper 命名空间不起作用
【发布时间】:2012-08-07 11:29:51
【问题描述】:

问题 1:

我已经开始学习 ASP.NET MVC。我做了一个简单的扩展方法,像这样:

namespace MvcTestz  //Project is also named as "MvcTestz"
{
  public static class SubmitButtonHelper //extension method.
  {
    public static string SubmitButton(this HtmlHelper helper,string buttonText)
    {
        return string.Format("<input type=\"submit\" value=\"{0}\">",buttonText);
    }
  }
}

然后我将自定义 HtmlHelper 的命名空间添加到 Web.Config 中,就像这样

  <namespaces>
    <!--other namespaces-->
    <add namespace="MvcTestz"/>
    <!--other namespaces-->
  </namespaces>

这样我就可以在 razor 视图中使用智能感知,但自定义 Helper 没有出现在一个视图中 (Home/View/About.cshtml)

所以在另一个视图中(Home/View/Index.cshtml) 我通过@using MvcTestz; 语句添加了命名空间。

问题二:

在 WebApp 执行时主页(Home/View/Index.cshtml) 显示输入按钮文本而不将其呈现为 HTML。

在关于页面(Home/View/About.cshtml) 服务器上生成错误。 (Click for Enlarged)

更新:

  1. Intellisense 问题已解决,我必须编辑视图目录中的 Web.Config。已解决。
  2. HtmlString 如果我想渲染一个 Html 按钮,应该使用它。已解决。

【问题讨论】:

    标签: asp.net asp.net-mvc visual-studio-2010 razor html-helper


    【解决方案1】:

    试试这样的,

    对于您的扩展方法,请使用MvcHtmlString.Create

    public static MvcHtmlString MySubmitButton(this HtmlHelper helper, string buttonText)
    {
      return MvcHtmlString.Create("<input type='submit' value='" + buttonText + "' />");
    }
    

    并包括您的参考见下文

      <system.web.webPages.razor>
        <namespaces>
            <!- add here.....  -->
            <add namespace="MvcTestz"/>
    
          </namespaces>        
      </system.web.webPages.razor>
    

    【讨论】:

    • 感谢 Yasser bhai 的帮助
    • 你叫我“bhai”让我开心:)
    【解决方案2】:

    问题一:

    Razor 命名空间应在 web.config 的 &lt;system.web.webPages.razor&gt; 节点中注册:

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

    问题2:在你的助手中使用HtmlString而不是字符串:

    public static HtmlString SubmitButton(this HtmlHelper helper, string buttonText)
    {
        return new HtmlString(string.Format("<input type=\"submit\" value=\"{0}\">", buttonText));
    }
    

    【讨论】:

      猜你喜欢
      • 2014-07-17
      • 1970-01-01
      • 2011-11-27
      • 1970-01-01
      • 2015-11-14
      • 2015-02-22
      • 2012-05-16
      • 1970-01-01
      • 2012-09-16
      相关资源
      最近更新 更多