EditorFor的最小值和最大值
我一直在尝试这段代码来设置我的EditorFor
的最小值和最大值:
I've been trying this code to set minimum and maximum on my EditorFor
:
<label id="LbStartYear" style="width: 200px">From Date: @Html.EditorFor(model => model.SelectedYearBegin, new { htmlAttributes = new { @min = "0", @max = "20" } })</label>
但是没有成功.从来没有设置最小值和最大值.我尝试删除了0
和20
的引号,也尝试了使用@
和不使用@
的情况.
But no success. Minimum and Maximum are never set. I tried removing the quotation from 0
and 20
, also tried with and without the @
.
有什么想法吗?
只需在模型属性上使用Range
DataAnnotation属性.通过使用此属性,您可以限制用户输入不属于该范围的任何其他数字.
Simply use Range
DataAnnotation attribute on your model property. By using this attribute you can restrict user to enter any other number which doesn't fall in the range.
导入以下名称空间-
using System.ComponentModel.DataAnnotations;
using System.ComponentModel;
然后用Range
属性装饰您的属性-
And then decorate your property with Range
attribute -
[Range(0,20)]
public int SelectedYearBegin { get; set; }
有关范围属性的更多信息- https://msdn.microsoft.com/zh-cn/library/system.componentmodel.dataannotations.rangeattribute(v = vs.110).aspx
For more information on Range Attribute - https://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.rangeattribute(v=vs.110).aspx
您可以通过在Web.config中启用客户端验证-
You can get client side validation by enabling it in Web.config -
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
请确保您链接JQuery并保持不干扰,并验证JS文件.
Make sure you link JQuery unobtrusive and validate JS files.
或者,如果仍要为EditorFor
设置min
和max
,则需要获得MVC 5.1或更高版本.以下代码适用于MVC 5.1及更高版本.
Alternatively if you still want to set min
and max
for EditorFor
, then you need to get MVC 5.1 or higher. Below code works for MVC 5.1 and higher.
@Html.EditorFor(model => model.SelectedYearBegin, new { htmlAttributes = new { @min = "0", @max = "20" } })
如果您不想使用MVC 5.1和更高版本,则只需使用TextBoxFor
-
If you do not want to go for MVC 5.1 and higher, then simply use TextBoxFor
-
@Html.TextBoxFor(model => model.SelectedYearBegin, new { type = "number", min = 0, max = 100 })