Min and Max values for EditorFor

妖精的绣舞 提交于 2019-12-06 04:47:17

问题


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>

But no success. Minimum and Maximum are never set. I tried removing the quotation from 0 and 20, also tried with and without the @.

Any ideas?


回答1:


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.

Import following namespaces -

using System.ComponentModel.DataAnnotations;
using System.ComponentModel;

And then decorate your property with Range attribute -

[Range(0,20)]
public int SelectedYearBegin { get; set; }

For more information on Range Attribute - https://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.rangeattribute(v=vs.110).aspx

You can get client side validation by enabling it in Web.config -

 <add key="ClientValidationEnabled" value="true"/> 
 <add key="UnobtrusiveJavaScriptEnabled" value="true"/> 

Make sure you link JQuery unobtrusive and validate JS files.

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

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


来源:https://stackoverflow.com/questions/34639312/min-and-max-values-for-editorfor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!