Extending MVC3 HTML Helpers to include custom HTML5 Attribute
I know I can add custom attributes to any given helper using an anonymous type with the attribute and value specified for it to be rendered as a HTML5 attribute however im looking to achieve the same across all HTML Helpers in a given view triggered by an externally specified helper. Similar to the same functionality you receive from the un-obtrusive JavaScript helper where it render开发者_运维技巧s validation rules in the context of a form field's attributes.
Does anyone know if there is a "simple" way to inject these customisations into the helpers, or will I need to extend each of the helpers independently?
Cheers
You can't extend all methods from one centralized point (write code that will extend all your html helper methods by adding overload with additional 'htmlAttributes' parameter - may be it is possible by using IL methods generation, but it is hard way).
Each extension should be overload of your html helper method, and you can implement like in example:
public static class HtmlExtensions
{
public static string MyPager(this HtmlHelper html, string parameter1, int parameter2)
{
var builder = new TagBuilder("div");
GenerateMyPagerBody(builder , parameter1, parameter2); // insert body into tag
return builder.ToString(TagRenderMode.SelfClosing);
}
public static string MyPager(this HtmlHelper html, string parameter1, int parameter2, object htmlAttributes)
{
var builder = new TagBuilder("div");
GenerateMyPagerBody(builder , parameter1, parameter2);
builder.MergeAttributes(new RouteValueDictionary(htmlAttributes));
return builder.ToString(TagRenderMode.SelfClosing);
}
}
精彩评论