DropdownListFor default value

前端 未结 5 516
無奈伤痛
無奈伤痛 2020-11-28 06:38

Is there a simple way to add a \"--Please select--\" default option to a DropDownListFor in MVC 3?

5条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-28 07:14

    I like the following method:

    @Html.DropDownListFor(m => m.SelectedId, new SelectList(Model.Items, "Id", "Name"), new SelectListItem() { Text = "None", Value = "", Selected = true }.Text, new { @class = "form-control search-select-input btn btn-block btn-outline-secondary dropdown-toggle p-1" })

    Where Items is an IEnumerable of type you want to display in the dropdown. And you can change out whatever bootstrap classes you want in the last parameter.

    This way allows you to set a default label and specify the value of the label if needed.

提交回复
热议问题