您需要一个视图模型,尤其是当您想同时选择多个城市时。例如:
public class RideViewModel
{
public Guid Id { get; set; }
public DateTime DateAndTime { get; set; }
public int FromCityId { get; set; }
public List<int> ToCityIds { get; set; }
public IEnumerable<SelectListItem> CityChoices { get; set; }
}
请注意,视图模型上没有 List<City> 属性。相反,ToCityIds 将存储从列表框中选择的 id 值,CityChoices 将用于填充列表框。您不能从列表框中发布完整的 City 对象,只能发布像 int 这样的简单类型。因此,在 POST 中,您将使用来自 ToCityIds 的值从数据库中查找 City 实例。实体上的 From 属性也是如此。
现在,在您的控制器中:
private void PopulateCityChoices(RideViewModel model)
{
model.CityChoices = db.Cities.Select(m => new SelectListItem
{
Value = m.Id,
Text = m.Name
});
}
public ActionResult Create()
{
var model = new RideViewModel();
PopulateCityChoices(model);
return View(model);
}
[HttpPost]
public ActionResult Create(RideViewModel model)
{
if (ModelState.IsValid)
{
// Create new `Ride` and map data over from model
var ride = new Ride
{
Id = Guid.NewGuid(),
DateAndTime = model.DateAndTime,
From = db.Cities.Find(model.FromCityId),
To = db.Cities.Where(m => m.ToCityIds.Contains(m.Id))
}
db.Rides.Add(ride);
db.SaveChanges();
}
// Must repopulate `CityChoices` after post if you need to return the form
// view again due to an error.
PopulateCityChoices(model);
return View(model);
}
最后在您的视图中将模型声明更改为:
@model Namespace.To.RideViewModel
然后添加您的From 选择列表和To 列表框:
@Html.DropDownListFor(m => m.FromCityId, Model.CityChoices)
@Html.ListBoxFor(m => m.ToCityIds, Model.CityChoices)
您可以对两者使用相同的选项,因为它们都在选择城市。