自定义编辑模板和htmlattributes



我正在尝试使用editor为自定义模板。

我想创建一个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这样的额外的htmlattribute时,我不明白我必须如何在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

您正在使用将对象作为 additionalViewData传递的EditorFor()的过载。您可以从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 = "..."(

,否则您不需要领先的@

最新更新