Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set numeric editorfor min, max and default values in Razor

I have an int value that I want to render as a numeric up down with an id that is"Quantity" , so I do the following in razor:

<div class="field-label">@Html.LabelFor(m => model.Quantity)</div>
<div class="field-editor">@Html.EditorFor(m => model.Quantity, null, "Quantity")</div>

In chrome this gives me the right UI, however I would like to set the min, max and default value so it works like the following code does.

<input id="Quantity" type="number" name="quantity" min="0" max="10" value="0" >
like image 504
user3648646 Avatar asked Jun 16 '14 14:06

user3648646


People also ask

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

Simply use Range DataAnnotation attribute on your model property.

What is the difference between TextBoxFor and EditorFor?

TextBoxFor: It will render like text input html element corresponding to specified expression. In simple word it will always render like an input textbox irrespective datatype of the property which is getting bind with the control. EditorFor: This control is bit smart.

What is EditorFor?

EditorFor<TModel,TValue>(HtmlHelper<TModel>, Expression<Func<TModel,TValue>>, String, String, Object) Returns an HTML input element for each property in the object that is represented by the expression, using the specified template, HTML field name, and additional view data.

What is Razor syntax in MVC?

Razor is a markup syntax that lets you embed server-based code into web pages using C# and VB.Net. It is not a programming language. It is a server side markup language. Razor has no ties to ASP.NET MVC because Razor is a general-purpose templating engine.


1 Answers

You can do this via the "object AddiditonalViewData" overload of the @Html.EditorFor function. Then specify htmlAttributes like so:

@Html.EditorFor(m => Model.Quantity, new {htmlAttributes = new {min = 0, max = 20} } )

Note that the "value" is set to the actual value of the Quantity property, no matter what you define in the htmlAttributes.

like image 128
MerlinK Avatar answered Oct 20 '22 00:10

MerlinK