DropDownListFor, selected = true 不起作用
Yup.
但我无法在下拉列表中选择一个指定的选项,总是首先选择第一个选项。
当你使用
// I don't recommend using the variable `model` for the lambda
Html.DropDownListFor(m => m.<MyId>, <IEnumerable<SelectListItem>> ...
MVC 忽略.selected
并验证m.<MyId>
值与中的值的比较<IEnumerable<SelectListItem>>
.
public class DropDownModel
{
public int ID3 { get; set; }
public int ID4 { get; set; }
public int ID5 { get; set; }
public IEnumerable<SelectListItem> Items { get; set; }
}
public ActionResult Index()
{
var model = new DropDownModel
{
ID3 = 3, // Third
ID4 = 4, // Second
ID5 = 5, // There is no "5" so defaults to "First"
Items = new List<SelectListItem>
{
new SelectListItem { Text = "First (Default)", Value = "1" },
new SelectListItem { Text = "Second (Selected)", Value = "2", Selected = true },
new SelectListItem { Text = "Third", Value = "3" },
new SelectListItem { Text = "Forth", Value = "4" },
}
};
return View(model);
}
<div>@Html.DropDownListFor(m => m.ID3, Model.Items)</div>
<div>@Html.DropDownListFor(m => m.ID4, Model.Items)</div>
<div>@Html.DropDownListFor(m => m.ID5, Model.Items)</div>
Result:
dotnetfiddle.net 示例 https://dotnetfiddle.net/sPDf59