Extending MVC3 HTML Helpers to include custom HTML5 Attribute

本小妞迷上赌 提交于 2019-12-11 04:01:44

问题


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 renders 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


回答1:


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);
    }
}


来源:https://stackoverflow.com/questions/6262473/extending-mvc3-html-helpers-to-include-custom-html5-attribute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!