自定义 EditorFor Template 和 htmlAttributes

Jua*_*gal 4 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,'')" } )
Run Code Online (Sandbox Code Playgroud)

我称之为

@Html.EditorFor(x => x.ExampleIntField)
Run Code Online (Sandbox Code Playgroud)

它呈现一个 <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" } } )
Run Code Online (Sandbox Code Playgroud)

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

小智 6

您正在使用过载EditorFor()是传递对象additionalViewData。您可以在模板中从ViewDataDictionary

@model int?
@{ var attributes = ViewData["htmlAttributes"]; } // returns { @readonly = "readonly" }
Run Code Online (Sandbox Code Playgroud)

然后您可以将其与现有属性合并并在TextBoxFor()方法中使用。

@{
    var htmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(attributes);
    htmlAttributes.Add("oninput", "this.value=this.value.replace(/[^0-9]/g,'')";
}
@Html.TextBoxFor(model => model, htmlAttributes)
Run Code Online (Sandbox Code Playgroud)

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