使用DropDownListFor添加'required'属性

时间:2013-09-09 18:48:52

标签: c# razor

我有这个:

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

并希望将其呈现为:

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

我该怎么做?

3 个答案:

答案 0 :(得分:23)

使用此:

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

它不会达到速记<select required但它应该具有相同的效果。虽然我发现你可以使用

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

哪个有点难看。

答案 1 :(得分:0)

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

答案 2 :(得分:0)

尝试以下

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