就我个人而言,我会跳过“AllInOneModel”并坚持将单个城市发送到视图中。
控制器动作可能看起来有点像这样。
public ActionResult Index()
{
//TODO: get current cities from database
List<City> cities = new List<City>
{
new City { CityID = 1, CityName = "City1" },
new City { CityID = 2, CityName = "City2" },
new City { CityID = 3, CityName = "City3" }
};
// Create the list of selectlistitems to populate the dropdown
List<SelectListItem> listItems = new List<SelectListItem>();
foreach(var c in cities)
{
listItems.Add(new SelectListItem { Value = c.CityID.ToString(), Text = c.CityName });
}
//Throw them into viewbag
ViewBag.ListItems = listItems;
//TODO get some city (perhaps from db) to send to view
var city = new City { CityID = 1, CityName = "City1" };
return View(city);
}
然后你会以这种方式渲染视图。
@model IBilik.Models.City
@Html.DropDownListFor(model => model.CityID, ViewBag.ListItems as List<SelectListItem>)