2015-08-13 90 views
0

关于类似主题有几个问题。但是,他们并没有真正解决我的问题。我可以通过数据注释更改EditorFor的宽度吗?

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;" }) 

我得到这个:

enter image description here

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

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

+0

您使用的是MVC-5.1 +。如果不是,则不能将html属性传递给默认编辑器模板(您将需要创建自己的自定义'EditorTemplate')。或者使用'@ Html.TextBoxFor(m => m.Quantity,new {type =“number”,style =“width:30px;”})' –

+0

MVC 4 @StephenMuecke。我将升级为下一个项目。 –

+0

@StephenMuecke谢谢你。你能发布这个答案吗?,我不确定自定义EditorTemplate。你可能会被授予积分 –

回答

1

从评论中,您使用的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()方法使所有元素。

+0

谢谢,我认为这是有用的信息。 –

相关问题