这里是一个可行的解决方法,我们需要在Controller中使用ViewBag来传递下拉列表所需的数据,然后确保当页面重新加载时,下拉列表的内容能够被正确的重新填充。
public IActionResult Create()
{
// 获取下拉列表所需的数据
ViewBag.items = new SelectList(db.Items, "ItemId", "Name");
return View();
}
[HttpPost]
public IActionResult Create(MyViewModel model)
{
if (!ModelState.IsValid)
{
// 如果模型验证失败,则需要重新返回下拉列表所需的数据
ViewBag.items = new SelectList(db.Items, "ItemId", "Name", model.ItemId);
return View(model);
}
// 此处省略添加数据的代码
return RedirectToAction("Index");
}
在视图中,我们需要使用Html.DropDownListFor()方法来生成下拉列表,并传入需要被选中的项目的值。
@Html.DropDownListFor(m => m.ItemId, (SelectList)ViewBag.items, "Please select an item", new { @class = "form-control" })