我有一个自定义助手,我在其中接收 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 内容是:
请注意,“类”显示正确,但扩展助手中的其他属性位于字典中,我做错了什么?
如果可能的话,我只想更改扩展助手而不是编辑器模板,所以我认为传递给 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/