How to set numeric editorfor min, max and default

2019-06-16 00:54发布

问题:

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

回答1:

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.