要使用“选定项”填充视图中的下拉列表,我可以创建一个 SelectList,如下所示:
ViewData["MyDropDown"] = new SelectList(_context.DataTable, "ItemID", "ItemName", ItemID);
但是,我有一个带有自定义 ListItem 的下拉菜单,如下所示:
var dropDownData= await _context.DataTable.Select(u => new SelectListItem { Value = u.ItemID.ToString(), Text = u.ItemName}).ToListAsync();
dropDownData.Add(new SelectListItem() { Value = "", Text = "-- Select -- "});
ViewData["MyDropDown"] = dropDownData;
如果我想让“-- Select --”选项成为所选选项,我只需要在该行添加“, Selected = true
”即可。 现在,如何从 _context 生成的选项中指定所选项目?
谢谢!
public IActionResult Index()
{
var dropDownData = _context.Customers
.Select(u => new SelectListItem { Value = u.Id.ToString(), Text = u.Name })
.ToList();
dropDownData.Add(new SelectListItem() { Value = "", Text = "-- Select -- " });
var defaultSelectedID = 3;
foreach (var item in dropDownData)
{
if (item.Value == defaultSelectedID.ToString())
{
item.Selected = true;
break;
}
}
ViewData["MyDropDown"] = dropDownData;
return View();
}
页码:
<form method="post" asp-action="Index">
<select name="SelectedOfficerId">
@foreach (var item in (List<SelectListItem>)ViewData["MyDropDown"])
{
<!option value="@item.Value" @(item.Selected ? "selected" : "")>@item.Text</!option>
}
</select>
<button type="submit">Submit</button>
</form>
我设置了一些种子数据: