使用 DropDownListFor 添加 'required' 属性

本文关键字:属性 required DropDownListFor 添加 使用 | 更新日期: 2023-09-27 18:30:39

>我有这个:

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

并希望将其呈现为:

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

我该怎么做?

使用 DropDownListFor 添加 'required' 属性

使用这个:

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

这有点丑。

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

尝试以下操作

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