您的代码中可能存在一些问题:
1) 避免使用 viewmodel 属性名称作为 ViewBag 属性名称,因为这可能会导致两者混淆。
2) 通过将第二个参数设置为空值,您不会在 DropDownList 助手中填充任何内容,请使用包含 SelectList 或 List<SelectListItem> 的 ViewBag 属性来填充它。
3) 为每个视图模型属性使用强类型 DropDownListFor。
基于以上几点,控制器动作应该是这样的:
public ActionResult Create(int id)
{
var bookings = db.Bookings.Include(b => b.Room).Include(b => b.Register);
var model = new ViewModel();
// use query to get both selected IDs
model.RoomId = bookings.Where(...).Select(x => x.RoomId).FirstOrDefault();
model.CustomerId = bookings.Where(...).Select(x => x.CustomerId).FirstOrDefault();
ViewBag.RoomList = new SelectList(db.Rooms, "RoomID", "RoomType");
ViewBag.CustomerList = new SelectList(db.Registers, "id", "username");
return View(model);
}
并且两个下拉列表都应该使用强类型帮助器,如下例所示:
@Html.DropDownListFor(model => model.RoomId, ViewBag.RoomList as SelectList, "-- Select Room --", new { @class = "form-control" })
@Html.DropDownListFor(model => model.CustomerId, ViewBag.CustomerList as SelectList, "-- Select Customer --", new { @class = "form-control" })
注意:最好在具有SelectList/List<SelectListItem> 类型的视图模型属性中填充选项列表并将其直接传递给视图:
型号
public List<SelectListItem> RoomList { get; set; }
public List<SelectListItem> CustomerList { get; set; }
控制器动作
public ActionResult Create(int id)
{
var bookings = db.Bookings.Include(b => b.Room).Include(b => b.Register);
var model = new ViewModel();
// use query to get both selected IDs
model.RoomId = bookings.Where(...).Select(x => x.RoomId).FirstOrDefault();
model.CustomerId = bookings.Where(...).Select(x => x.CustomerId).FirstOrDefault();
model.RoomList = db.Rooms.Select(x => new SelectListItem { Text = x.RoomType, Value = x.RoomID }).ToList();
model.CustomerList = db.Registers.Select(x => new SelectListItem { Text = x.username, Value = x.id }).ToList();
return View(model);
}
查看
@Html.DropDownListFor(model => model.RoomId, Model.RoomList, "-- Select Room --", new { @class = "form-control" })
@Html.DropDownListFor(model => model.CustomerId, Model.CustomerList, "-- Select Customer --", new { @class = "form-control" })