Search code examples
asp.netasp.net-mvcvisual-studio-2010razorhtml-helper

Adding HtmlHelper NameSpace in Web.Config does not work


Problem No 1:

I have started learning ASP.NET MVC. I have made a simple extension method, like this:

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

Then I have added namespace of the Custom HtmlHelper in to the Web.Config ,like this

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

So that I could use intellisense in the razor View ,but it custom Helper didnt showed up in one View (Home/View/About.cshtml).

enter image description here

So in another view (Home/View/Index.cshtml) I added namespace by @using MvcTestz; statement.

Problem No 2:

Upon WebApp execution Home page(Home/View/Index.cshtml) shows input button text without rendering it into HTML.

enter image description here On the About page (Home/View/About.cshtml) sever generates error. (Click for Enlarged) enter image description here

Update:

  1. Intellisense problem solved , I had to edit the Web.Config present in the View Directory. SOLVED.
  2. HtmlString Should be used if I want to render a Html button. SOLVED.

Solution

  • Problem 1:

    Razor namespaces should be registred in the <system.web.webPages.razor> node in web.config:

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

    Problem 2: Use HtmlString instead of string in your helper:

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