asp.net-mvc - 如何在自定义助手中合并 htmlAttributes

标签 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,其中包含“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

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

如果可能的话,我只想更改扩展助手而不是编辑器模板,所以我认为传递给 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/

相关文章:

c# - 扩展方法与实例方法与静态类

asp.net-mvc - 流利的验证不起作用的长度

asp.net-mvc - 从命令行在 IISExpress 中运行 ASP.NET

javascript - 异步更改 javascript 函数/"class"的参数?

kotlin - Kotlin:如何在扩展名中调用具有相同名称的方法?

ios - 从 Objective-C 调用 Swift 扩展函数的语法

c# - 如何从列表集合中删除对象?

c# - 在 Azure 中生成并执行工作进程

jquery event.target 属性在 asp.net 中不起作用

attributes - 在源代码上添加一个新属性,该属性会传播到 LLVM 中的 MC 级别?