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?
Editor() or Html. EditorFor() extension methods generate HTML elements based on the data type of the model object's property. The following table list the data types and releted HTML elements: DataType. Html Element.
The EditorFor() Helper is just like the TextBoxFor() Helper above with the exception that it will actually read metadata and other attributes from the Model to determine the appropriate type of element to render (such a checkbox for a boolean field) and it will map those values accordingly from the Model.
Simply use Range DataAnnotation attribute on your model property.
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 })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With