Custom HTML helper class in MVC
I've been using custom HTML helper extensions for some time now. Lately I've decided it would be nice to use helper that look like this
<%: Style.MyCustomExtensionMethod(...) %>
or
@Style.MyCustomExtensionMethod("abcd")
I sear开发者_StackOverflow中文版ched all over the net but always ran into custom HTML helpers that are called via Html.
I also inherited from HtmlHelper class like this
public static class Style : HtmlHelper
{
public static string test(this HtmlHelper helper, string text)
{
return text;
}
}
but that didn't work (in the View it says it cannot find method test() that takes one parameter.
If you want to achieve such syntax in your view you could always:
public static class Style
{
public static MvcHtmlString MyCustomExtensionMethod(string foo)
{
...
}
}
Obviously because you are not extending an HtmlHelper
you no longer have access to the HttpContext which limits the usefulness of such thing.
Another possibility is to modify the base class all your razor views are deriving from by extending WebViewPage
and adding a custom property to which you could write extension methods later. The question you have to ask yourself is: is it worth it?
Personally I find nothing wrong/ugly/incorrect about:
@Html.MyCustomExtensionMethod("abcd")
or:
@Url.MyCustomExtensionMethod("abcd")
Those are the de-facto standards in ASP.NET MVC and every developer should be familiar with. It's also easier with Intellisense and discoverability of your custom helpers.
精彩评论