How to create HtmlHelper extensions with Razor?
I saw this syntax:
@helper IncludeJS(string url)
{
<script src="@url" type="text/javascript"></script>
}
Placed on a .cshtml
file on Views\Helpers
. But then it is not recognized on views when using either:
Html.IncludeJS("")
IncludeJS("")
And I get this error开发者_开发百科:
CS1061: 'System.Web.Mvc.HtmlHelper<dynamic>' does not contain a definition for...
How can I create a custom HtmlHelper extension and use it on MVC3 (Razor)?
Helpers create normal page methods, not extension methods:
@IncludeJS("")
If you want to create an Html
extension method, you'll need to create a normal extension method (in a .cs
file) for the HtmlHelper
class.
If you do that, you can use the TagBuilder
class.
EDIT: The Views\Helpers
feature was dropped before RTM.
I got this same error because I had this:
<system.web>
<pages>
<namespaces>
<add namespace="MyNamespace"/>
When I needed this:
<system.web.webPages.razor>
<pages>
<namespaces>
<add namespace="MyNamespace"/>
In other words, there are multiple tags in the Web.Config in /Views, especially if you're using more view engines than Razor. You need to make sure you add this line to the Razor section if you want your HtmlHelper extensions to show up in your cshtml files.
精彩评论