【问题标题】:Adding the 'required' attribute with DropDownListFor使用 DropDownListFor 添加“必需”属性
【发布时间】:2013-09-09 18:48:52
【问题描述】:

我有这个:

@Html.DropDownListFor(x => x.SelectedValue, new SelectList(Model.SomeList, "Value", "Text"))

并且希望它被渲染成这样:

<select required>
    <option>...</option>
    ...

我该怎么做?

【问题讨论】:

标签: c# razor


【解决方案1】:

使用这个:

@Html.DropDownListFor(x => x.SelectedValue, new SelectList(Model.SomeList, "Value", "Text"), new {required = "required"})

它不会实现简写&lt;select required,但它应该具有相同的效果。虽然我发现你可以使用

来实现那个确切的元素
@Html.DropDownListFor(x => x.SelectedValue, new SelectList(Model.SomeList, "Value", "Text"), new {required = (string)null})

这有点难看。

【讨论】:

  • new {required = String.Empty} 也可以这样做 - 我正要尝试一下 :)
  • new { required = default(string) } 生成简写 &lt;select ... required&gt;
【解决方案2】:

VB.NET

@Html.DropDownListFor(Function(Model) Model.ProgramTypeId, New SelectList(Model.allPrograms, 
"ProgramTypeId", "ProgramName"), "Select Program....", 
New With {Key .class = "form-control", Key .required = "Required"})

【讨论】:

    【解决方案3】:

    试试下面的

    @Html.DropDownList("PlanType", null, "Select Plan Type", htmlAttributes: new { @class = "form-control", required = "Select Plan Type" })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-04-27
      • 1970-01-01
      • 1970-01-01
      • 2014-01-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多