我有一个自定义帮助器,在其中接收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方法必须返回在参数中使用“new {@class =“form-control”}“”接收到的合并的htmlAttributes:
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

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

如果可能的话,我只想更改扩展助手而不是编辑器模板,所以我认为传递给EditorFor的RouteValueDictionary需要强制转换为匿名对象...

最佳答案

我解决了现在将所有“编辑器模板”更改为以下行的问题:

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

关于asp.net-mvc - 如何在自定义帮助器中合并htmlAttributes,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26246378/

10-12 00:45