自定义 EditorFor Template 和 htmlAttributes [英] Custom EditorFor Template and htmlAttributes

查看:7
本文介绍了自定义 EditorFor Template 和 htmlAttributes的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 EditorFor 自定义模板.

I'm trying to use EditorFor custom templates.

我想创建一个 Int32 和十进制模板来呈现带有一些验证的输入.

I want to create a Int32 and decimal templates to render the inputs with some validations.

这就是我正在尝试的

@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 模板中接收它.

To here everything works, but when I try to pass extra htmlAttributes like readonly I don't understand how I must receive it in EditorFor template.

示例

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

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

I tried this I got the exact same <input type="text", oninput="this.value=this.value.replace(/[^0-9]/g,'')" rendered without readonly attribute

推荐答案

您正在使用 重载 EditorFor()code> 将对象作为 additionalViewData 传递.您可以从 ViewDataDictionary

You are using the overload of EditorFor() that passes the object as additionalViewData. You can read that within the template from the ViewDataDictionary

@model int?
@{ var attributes = ViewData["htmlAttributes"]; } // returns { @readonly = "readonly" }

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

which you could then merge with your existing attributes and use in the TextBoxFor() method.

@{
    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 = "...")

Note that TextBoxFor() generates type="text" so there is no need to add it again. In addition, you do not need the leading @ unless its a reserved keyword (for example @class = "...")

这篇关于自定义 EditorFor Template 和 htmlAttributes的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆