MVC5:如何指定表单控件来限制小数位数?
MVC5 : How do I specify form-control to limit the number of decimal places?
我有以下小数字段:
[DisplayFormat(DataFormatString = "{0:n2}", ApplyFormatInEditMode = true)]
public decimal MyDecimal { get; set; }
在我的 Razor 视图中
<td>Price</td>
<td>
@Html.EditorFor(model => model.MyDecimal, new { htmlAttributes = new { @class = "form-control decimal-small inline" } })
@Html.ValidationMessageFor(model => model.MyDecimal, "", new { @class = "text-danger" })
</td>
我希望用户最多只能在小数分隔符后放置 2 个数字。在许多 post 中,我看到 DisplayFormat 应该可以工作,但它在编辑模式下没有任何作用。在我的编辑字段中,我仍然可以在分隔符后面放置 2 个以上的数字
我也试过了
[DisplayFormat(DataFormatString = "{0:0.00}", ApplyFormatInEditMode = true)]
public decimal MyDecimal { get; set; }
仍然没有区别。
我认为您期望 [DisplayFormat] 属性的作用不同。该属性表示,数据应该如何 DISPLAYED,而不是输入。
您的解决方案有效,并且您的电话号码以应用的格式显示,不是吗?
您要实现的是 输入掩码 ,这是一个 client-side 功能。请参阅以下链接以了解更多信息:
- How to implement input masking with ASP.NET MVC
- http://www.codeproject.com/Tips/642477/Input-Masking-in-MVC-using-Data-Annotation
- Input mask MVC unmask in controller
编辑:
我已经进行了快速测试
视图模型:
[DisplayFormat(DataFormatString = "{0:0.00}",ApplyFormatInEditMode = true)]
public decimal Test {
get { return (decimal) 1.345; } }
并查看:
@Html.EditorFor(model=>model.Test, new { htmlAttributes = new { @class = "form-control decimal-small inline" } })
它显示:
作为替代方案,您可以尝试:
@Html.TextBoxFor(model=>model.Test,"{0:0.00}")
我有以下小数字段:
[DisplayFormat(DataFormatString = "{0:n2}", ApplyFormatInEditMode = true)]
public decimal MyDecimal { get; set; }
在我的 Razor 视图中
<td>Price</td>
<td>
@Html.EditorFor(model => model.MyDecimal, new { htmlAttributes = new { @class = "form-control decimal-small inline" } })
@Html.ValidationMessageFor(model => model.MyDecimal, "", new { @class = "text-danger" })
</td>
我希望用户最多只能在小数分隔符后放置 2 个数字。在许多 post 中,我看到 DisplayFormat 应该可以工作,但它在编辑模式下没有任何作用。在我的编辑字段中,我仍然可以在分隔符后面放置 2 个以上的数字
我也试过了
[DisplayFormat(DataFormatString = "{0:0.00}", ApplyFormatInEditMode = true)]
public decimal MyDecimal { get; set; }
仍然没有区别。
我认为您期望 [DisplayFormat] 属性的作用不同。该属性表示,数据应该如何 DISPLAYED,而不是输入。 您的解决方案有效,并且您的电话号码以应用的格式显示,不是吗? 您要实现的是 输入掩码 ,这是一个 client-side 功能。请参阅以下链接以了解更多信息:
- How to implement input masking with ASP.NET MVC
- http://www.codeproject.com/Tips/642477/Input-Masking-in-MVC-using-Data-Annotation
- Input mask MVC unmask in controller
编辑:
我已经进行了快速测试 视图模型:
[DisplayFormat(DataFormatString = "{0:0.00}",ApplyFormatInEditMode = true)]
public decimal Test {
get { return (decimal) 1.345; } }
并查看:
@Html.EditorFor(model=>model.Test, new { htmlAttributes = new { @class = "form-control decimal-small inline" } })
它显示:
作为替代方案,您可以尝试:
@Html.TextBoxFor(model=>model.Test,"{0:0.00}")