gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 01:23:00 25 4
gpt4 key购买 nike

我有一个自定义助手,我在其中接收 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com