如何在Custom Helper中合并htmlAttributes

Osw*_*ldo 6 asp.net-mvc extension-methods attributes

我有一个自定义助手,我收到一个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 });
   ...
}
Run Code Online (Sandbox Code Playgroud)

MergeAnonymous方法必须返回参数中收到的合并后的htmlAttributes,其中包含"new {@class ="form-control"}":

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;
}
Run Code Online (Sandbox Code Playgroud)

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

@model decimal?

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

@Html.TextBox("", string.Format("{0:c}", Model.ToString()), htmlAttributes)
Run Code Online (Sandbox Code Playgroud)

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

点击这里查看图片

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

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

Osw*_*ldo 5

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

var htmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(ViewData["htmlAttributes"]);
Run Code Online (Sandbox Code Playgroud)

为了这:

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

和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;
}
Run Code Online (Sandbox Code Playgroud)