我正在嘗試爲EditorFor創建一個自定義幫助器。我想從模型中獲取字符串長度並將其添加到html屬性中。MVC EditorFor自定義幫助器
到目前爲止我有以下內容,但是這並不適用添加的新屬性。在return htmlHelper.EditorFor(expression, ViewData)
public static IHtmlString MyEditorFor<TModel, TValue>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TValue>> expression, object ViewData, bool disabled = false, bool visible = true)
{
var member = expression.Body as MemberExpression;
var stringLength = member.Member.GetCustomAttributes(typeof(StringLengthAttribute), false).FirstOrDefault() as StringLengthAttribute;
RouteValueDictionary viewData = HtmlHelper.AnonymousObjectToHtmlAttributes(ViewData);
RouteValueDictionary htmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(viewData["htmlAttributes"]);
if (stringLength != null)
{
htmlAttributes.Add("maxlength", stringLength.MaximumLength);
}
return htmlHelper.EditorFor(expression, ViewData);
}
'返回htmlHelper.EditorFor (表達式,ViewData)'不添加任何屬性。它只是使用傳遞給方法 –
的原始'ViewData'屬性如何編輯並返回屬性?我無法返回新的viewData對象,因爲它是不同的類型 – user3208483