Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Min and Max values for 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>

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?

like image 667
Alexandre Severino Avatar asked Jan 06 '16 17:01

Alexandre Severino


People also ask

What is EditorFor?

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.

What is the difference between TextBoxFor and EditorFor?

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.

Which attribute is used to specify min and max value for a model field?

Simply use Range DataAnnotation attribute on your model property.


1 Answers

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 })
like image 86
ramiramilu Avatar answered Nov 13 '22 09:11

ramiramilu