问题
Problem No 1:
Hi guys 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)
.
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.
(Home/View/About.cshtml)
sever generates error. (Click for Enlarged)
Update:
- Intellisense problem solved , I had to edit the Web.Config present in the View Directory.SOLVED.
HtmlString
Should be used if I want to render a Html button.SOLVED.
回答1:
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));
}
回答2:
try something like this,
For your extension method, use MvcHtmlString.Create
public static MvcHtmlString MySubmitButton(this HtmlHelper helper, string buttonText)
{
return MvcHtmlString.Create("<input type='submit' value='" + buttonText + "' />");
}
and to include your reference see below
<system.web.webPages.razor>
<namespaces>
<!- add here..... -->
<add namespace="MvcTestz"/>
</namespaces>
</system.web.webPages.razor>
来源:https://stackoverflow.com/questions/11896977/adding-htmlhelper-namespace-in-web-config-does-not-work