加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

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

发布时间:2020-12-16 03:55:03 所属栏目:asp.Net 来源:网络整理
导读:我有一个自定义助手,我收到一个htmlAttributes作为参数: public static MvcHtmlString CampoTModel,TValue( this HtmlHelperTModel helper,ExpressionFuncTModel,TValue expression,dynamic htmlAttributes = null){ var attr = MergeAnonymous(new { @clas
我有一个自定义助手,我收到一个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;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读