我正在尝试将数据加载到嵌套母版页中的下拉列表中,但视图中的模型始终为null。我怎么能这样做?
在模型中
public class AllInOneModel
{
public string City { get; set; }
public IEnumerable<City> cities { get; set; }
}
在控制器中
public ActionResult Add()
{
return View(new AllInOneModel());
}
在视图中
@model IBilik.Models.AllInOneModel
@Html.DropDownListFor(model => model.City,(SelectList)Model.cities)
答案 0 :(得分:0)
我个人会跳过&#34; AllInOneModel&#34;并坚持将单个城市送到视野。
控制器动作看起来有点像这样。
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>)