How to merge htmlAttributes in Custom Helper

前提是你 提交于 2019-12-05 09:30:33

I solved for now changing all my Editor Templates the line:

var htmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(ViewData["htmlAttributes"]);

for this:

var htmlAttributes = ViewData["htmlAttributes"] as IDictionary<string, object> ?? HtmlHelper.AnonymousObjectToHtmlAttributes(ViewData["htmlAttributes"]);

and the MergeAnonymous method to this:

static IDictionary<string,object> MergeAnonymous(object obj1, object obj2)
{
    var dict1 = new RouteValueDictionary(obj1);
    var dict2 = new RouteValueDictionary(obj2);
    IDictionary<string, object> result = new Dictionary<string, object>();

    foreach (var pair in dict1.Concat(dict2))
    {
        result.Add(pair);
    }

    return result;
}
Flavio
public static class CustomHelper
    {
        public static MvcHtmlString Custom(this HtmlHelper helper, string tagBuilder, object htmlAttributes)
        {
            var builder = new TagBuilder(tagBuilder);

            RouteValueDictionary customAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);

            foreach (KeyValuePair<string, object> customAttribute in customAttributes)
            {
                builder.MergeAttribute(customAttribute.Key.ToString(), customAttribute.Value.ToString());
            }

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