自定义EditorFor Template和htmlAttributes

时间:2018-04-27 12:00:05

标签: asp.net-mvc razor asp.net-mvc-5 editorfortemplate

我尝试使用EditorFor自定义模板。

我想创建一个Int32和十进制模板,以使用一些验证来呈现输入。

这就是我正在尝试的

@model int?

@Html.TextBoxFor(model => model, null, new { @type="text", @oninput = "this.value=this.value.replace(/[^0-9]/g,'')" } )

我称之为

@Html.EditorFor(x => x.ExampleIntField)

它呈现<input type="text", oninput="this.value=this.value.replace(/[^0-9]/g,'')"

到这里一切正常,但当我尝试传递像readonly这样的额外htmlAttributes时,我不明白我必须在EditorFor模板中接收它。

实施例

@Html.EditorFor(x => x.ExampleIntField, new { htmlAttributes = new { @readonly = "readonly" } } )

我试过这个,我得到了完全相同的<input type="text", oninput="this.value=this.value.replace(/[^0-9]/g,'')"呈现而没有readonly attribute

1 个答案:

答案 0 :(得分:4)

您正在使用EditorFor() additionalViewData传递对象ViewDataDictionary。您可以在@model int? @{ var attributes = ViewData["htmlAttributes"]; } // returns { @readonly = "readonly" }

的模板中阅读
TextBoxFor()

然后您可以将其与现有属性合并,并在@{ var htmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(attributes); htmlAttributes.Add("oninput", "this.value=this.value.replace(/[^0-9]/g,'')"; } @Html.TextBoxFor(model => model, htmlAttributes) 方法中使用。

TextBoxFor()

请注意,type="text"会生成@,因此无需再次添加。此外,您不需要前导@class = "...",除非它是保留关键字(例如navbar.html

相关问题