4

I have an EditorFor razor defined input box that sets the value for "Hours" that has it's data model bound:

@Html.EditorFor(modelItem => item.Hours, null, "weeklytargets[" + item.WeeklyTargetId + "].Hours")

When it's spit out to HTML it looks like so:

<input class="text-box single-line" data-val="true" data-val-number="The field Hours must be a number." id="weeklytargets_17__Hours" name="weeklytargets[17].Hours" type="number" value="10">

How can I add attributes min and max for this input box of type number?

LaRae White
  • 1,222
  • 3
  • 17
  • 35
  • 3
    ```EditorFor``` will try to find a template based on ```item.Hours``` datatype or uihints etc. If you know what sort of form element you want to render. A quick way would be ```Html.TextBoxFor(modelItem => item.Hours, new { type="number", min="0", max="100" })```. Alternatively, you might find this helpful: http://stackoverflow.com/questions/17742488/how-to-add-custom-data-attributes-and-classes-to-html-editorfor#answer-17743013 – Varinder Mar 20 '14 at 19:49

2 Answers2

2

Try using the additionalViewData parameter to pass in htmlAttributes. This way you can specify a min and max value:

@Html.EditorFor(
    expression: modelItem => item.Hours,
    templateName: null,
    htmlFieldName: "weeklytargets[" + item.WeeklyTargetId + "].Hours",
    additionalViewData: new
    {
        htmlAttributes = new
        {

            min = 0,
            max = int.MaxValue
        }
    })
2

This is working for me

@Html.TextBoxFor(m => m.years_completed, new { @type="number", min = "1", max = "10" })
Ravi Ram
  • 24,078
  • 21
  • 82
  • 113