asp.net-mvc – 如何在Custom Helper中合并htmlAttributes

我有一个自定义助手,我收到一个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,其中包含“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;
}

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

@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

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

如果可能的话,我想只更改Extension Helper而不是Editor Template,所以我认为传递给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;
}

相关文章

这篇文章主要讲解了“WPF如何实现带筛选功能的DataGrid”,文...
本篇内容介绍了“基于WPF如何实现3D画廊动画效果”的有关知识...
Some samples are below for ASP.Net web form controls:(fr...
问题描述: 对于未定义为 System.String 的列,唯一有效的值...
最近用到了CalendarExtender,结果不知道为什么发生了错位,...
ASP.NET 2.0 page lifecyle ASP.NET 2.0 event sequence cha...