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