如何在Custom Helper中合并htmlAttributes

时间:2014-10-07 22:32:52

标签: asp.net-mvc attributes extension-methods

我有一个自定义助手,我收到一个htmlAttributes作为参数:

public static MvcHtmlString Campo<TModel, TValue>(
            this HtmlHelper<TModel> helper,
            Expression<Func<TModel, TValue>> expression,
            dynamic htmlAttributes = null)
{
   var attr = MergeAnonymous(new { @class = "form-control"}, htmlAttributes);
   var editor = helper.EditorFor(expression, new { htmlAttributes = attr });
   ...
}

MergeAnonymous方法必须返回参数中收到的合并后的htmlAttributes&#34; new {@class =&#34; form-control&#34;}&#34;:

static dynamic MergeAnonymous(dynamic obj1, dynamic obj2)
{
    var dict1 = new RouteValueDictionary(obj1);

    if (obj2 != null)
    {
        var dict2 = new RouteValueDictionary(obj2);

        foreach (var pair in dict2)
        {
            dict1[pair.Key] = pair.Value;
        }
    }

    return dict1;
}

在示例字段的编辑器模板中,我需要添加更多属性:

@model decimal?

@{
    var htmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(ViewData["htmlAttributes"]);
    htmlAttributes["class"] += " inputmask-decimal";
}

@Html.TextBox("", string.Format("{0:c}", Model.ToString()), htmlAttributes)

我在编辑模板的最后一行的htmlAttributes中有:

Click here to see the image

请注意&#34;类&#34;正确显示,但扩展助手的其他属性在字典中,我做错了什么?

如果可能,我想只更改Extension Helper而不是Editor Template,所以我认为传递给EditorFor的RouteValueDictionary需要转换为匿名对象...

2 个答案:

答案 0 :(得分:5)

我解决了现在更改所有编辑器模板的行:

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

为此:

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

和MergeAnonymous方法:

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

答案 1 :(得分:-1)

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