【问题标题】:Can I change the width of an EditorFor with data annotations?我可以使用数据注释更改 EditorFor 的宽度吗?
【发布时间】:2015-08-13 02:21:32
【问题描述】:

有几个关于类似主题的问题。但是,它们实际上并没有解决我的问题。

DisplayFormat for TextBoxFor in MVC

Display a formatted date in an EditorFor()

ASP.NET MVC EditorFor DateTime

我一直在搜索和阅读,但找不到答案。

我目前正在使用它来格式化我的输入框:

@Html.TextBoxFor(modelItem => item.Quantity, new { style = "width: 30px;" })

从我的模型中,我有简短的数据注释:

[Required, Range(1, 100)]
public int Quantity { get; set; }

所以我明白了:

当我使用时

@Html.EditorFor(modelItem => item.Quantity, new { style = "width: 30px;" })

我明白了:

我想要的是滚动,但要格式化宽度。

我想知道,有没有办法用data annotations 格式化EditorFor 的宽度?如果不是,那么制作这种格式的最简单方法是什么,以避免重复......bootstrapcss?我对内联样式不满意。

【问题讨论】:

  • 您使用的是 MVC-5.1+。如果不是,您不能将 html 属性传递给默认编辑器模板(您需要创建自己的自定义 EditorTemplate)。或者使用@Html.TextBoxFor(m => m.Quantity, new { type = "number ", style = "width: 30px;" })
  • 当然,我会给你几个选择。

标签: asp.net-mvc data-annotations editorformodel


【解决方案1】:

来自 cmets,您使用的是 MVC-4。除非您使用 MVC-5.1 或更高版本,否则您不能将 html 属性传递给 EditorFor() 方法(请参阅 release notes - 编辑器模板的引导支持部分

一种选择是使用TextBoxFor() 方法并传递type="number" 来呈现浏览器数字控件

@Html.TextBoxFor(m => m.Quantity, new { type = "number ", style = "width: 30px;" })

另一种方法是创建自定义EditorTemplate(比如_NumericControl.cshtml

@model System.Int32
@Html.TextBoxFor(m => m, new { type = "number ", style = "width: 30px;" })

并使用@Html.EditorFor(m => m.Quantity, "_NumericControl")调用它

但是,如果模板还包含其他 html 元素,例如 @Html.LabelFor(m => m)@Html.ValidationMessageFor(m => m) 甚至可能还有关联的按钮,这样 EditorFor() 方法就会呈现所有元素,这实际上只会有任何真正的好处。

【讨论】:

    猜你喜欢
    • 2018-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多