【问题标题】:How can I add min and max attributes to EditorFor input element?如何将 min 和 max 属性添加到 EditorFor 输入元素?
【发布时间】:2014-04-27 21:51:18
【问题描述】:

我有一个EditorFor razor 定义的输入框,用于设置绑定数据模型的“小时”值:

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

当它被吐出为 HTML 时,它看起来像这样:

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

如何为这个数字类型的输入框添加属性min和max?

【问题讨论】:

  • EditorFor 将尝试根据 item.Hours 数据类型或 uihints 等查找模板。如果您知道要呈现哪种表单元素。一个快速的方法是Html.TextBoxFor(modelItem =&gt; item.Hours, new { type="number", min="0", max="100" })。或者,您可能会发现这很有帮助:stackoverflow.com/questions/17742488/…

标签: html asp.net-mvc-4 razor attributes


【解决方案1】:

尝试使用additionalViewData 参数传入htmlAttributes。这样您就可以指定最小值和最大值:

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

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

【讨论】:

    【解决方案2】:

    这对我有用

    @Html.TextBoxFor(m => m.years_completed, new { @type="number", min = "1", max = "10" })
    

    【讨论】:

      猜你喜欢
      • 2013-01-12
      • 2018-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-06
      • 1970-01-01
      相关资源
      最近更新 更多