我正在尝试使用 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,'')"
到这里一切正常,但是当我尝试传递额外的 htmlAttributes 如 readonly
时我不明白如何在 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
渲染
最佳答案
您正在使用 overload 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 = "..."
)
关于asp.net-mvc - 模板和 htmlAttributes 的自定义编辑器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50061954/