asp.net-mvc - 模板和 htmlAttributes 的自定义编辑器

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

我正在尝试使用 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/

相关文章:

jquery - 将鼠标悬停在 MVC3 Razor WebGrid 行上时显示包含更多信息的工具提示

c# - 调用异步方法时使用 .Wait() 的情况是什么

asp.net-mvc - 如何清除 ASP.NET MVC 应用程序中文本框的发布数据?

javascript - 在提交和刷新页面时保留下拉列表的旧值

razor - 使用带有内联剑道网格的可排序小部件

javascript - Javascript 代码中的代码 Razor

c# - System.Web.WebPages 中的 MethodAccessException 将 mvc 3 迁移到 mvc 5

c# - 如何在 ASP.net 中安全地延迟 Web 响应?

javascript - 在 ASP .NET MVC 中允许 mime

c# - ASP.NET MVC $.post 调用返回字符串...需要有关 jqGrid 格式的帮助