我有一個自定義助手:如何,我收到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參數接收到「新{@class =」形式 - 控制「}」:
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是:
注意,「類」是正確顯示,但其他人的擴展幫助屬性是一個字典,什麼是我做錯了?
如果可能的話,我想只改變擴展幫助,而不是編輯模板,所以我覺得RouteValueDictionary傳給EditorFor需要轉換到一個匿名對象...
https://cpratt.co/html-editorfor-and-htmlattributes/ – 2017-05-13 05:13:53