MVC HTML Helper custom namespace
how I can create someth开发者_JS百科ing like this: Html.MyApp.ActionLink()? Thanks.
You can't do this. The only way you can add to the Html class is via an extension method. You cannot add "Extension Properties", which is what would be required for you to use Html.MyApp
. The closest you could come is Html.MyApp().Method(...)
Your best bet is probably to either include them as extension methods on Html, or create a new class completely (eg. MyAppHtml.Method(...)
or MyApp.Html.Method(...)
). There was a blog post around recently specifically showing an "Html5" class with these methods, but unfortunately my Google skills are failing me, and I can't find it :(
Added 13 Oct 2011 as asked in comment
To do something like Html.MyApp().ActionLink()
you need to create an extension method on HtmlHelper
, that returns an instance of a class with your custom method:
namespace MyHelper
{
public static class MyHelperStuff
{
// Extension method - adds a MyApp() method to HtmlHelper
public static MyHelpers MyApp(this HtmlHelper helper)
{
return new MyHelpers();
}
}
public class MyHelpers
{
public IHtmlString ActionLink(string blah)
{
// Wrap the html in an MvcHtmlString otherwise it'll be HtmlEncoded and displayed to the user as HTML :(
return new MvcHtmlString(string.Format("<a href=\"#\">{0}</a>", HttpUtility.HtmlEncode(blah)));
}
}
}
Note: You'll need to import the namespace this class is in in Web.config
, like this:
<?xml version="1.0"?>
<configuration>
<system.web.webPages.razor>
<pages>
<namespaces>
<add namespace="MyHelper"/>
</namespaces>
</pages>
</system.web.webPages.razor>
</configuration>
The change in the Web.Config file needs to be done in the config file for the view, not the global one
精彩评论