【问题标题】:MVC EditorFor Custom HelperMVC EditorFor 自定义助手
【发布时间】:2016-11-16 11:37:15
【问题描述】:

我正在尝试为 EditorFor 创建一个自定义助手。我想从模型中获取字符串长度并将其添加到 html 属性中。

到目前为止,我有以下内容,但这并不适用于添加的新属性。

    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);
    }

【问题讨论】:

  • return htmlHelper.EditorFor(expression, ViewData) 没有添加任何属性。它只是使用您传递给方法的原始ViewData 属性
  • 如何编辑它并返回属性?我无法返回新的 viewData 对象,因为它是不同的类型

标签: c# asp.net-mvc editorfor


【解决方案1】:

您在方法参数中返回原始 ViewData 属性,而不是 return htmlHelper.EditorFor(expression, ViewData) 上的自定义 HTML 属性集合。基于this answer,您的返回方法应更改为:

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, htmlAttributes); // use custom HTML attributes here
}

然后,像这样在视图端应用自定义 HTML 帮助器:

@Html.MyEditorFor(model => model.Property, new { htmlAttributes = new { @maxlength = "10" }})

编辑

此方法适用于 MVC 5 (5.1) 及更高版本,我不确定它是否适用于早期版本(请参阅此问题:Html attributes for EditorFor() in ASP.NET MVC)。

对于早期的 MVC 版本,更倾向于使用HtmlHelper.TextBoxFor,它当然具有maxlength 属性:

return htmlHelper.TextBoxFor(expression, htmlAttributes);

其他参考资料:

Set the class attribute to Html.EditorFor in ASP.NET MVC Razor View

HTML.EditorFor adding class not working

【讨论】:

  • EditorFor() 方法的第二个参数不接受 html 属性
猜你喜欢
  • 1970-01-01
  • 2016-10-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-04
相关资源
最近更新 更多