EditorFor的最小值和最大值 [英] Min and Max values for EditorFor

查看:119
本文介绍了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>

但是没有成功.从来没有设置最小值和最大值.我尝试删除了020的引号,也尝试了使用@和不使用@的情况.

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设置minmax,则需要获得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 })

这篇关于EditorFor的最小值和最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆