我的模型是一個通用的列表。我想使用DropDownList作爲外鍵屬性綁定。 我的代碼是如何使用DropDownListFor當模型是列表
型號
public class PersonViewModel
{
public int Id { get; set; }
public string LastName{get;set;}
public int NationalityId { get; set; }
}
public class Nationality
{
public int Id { get; set; }
public string Name { get; set; }
}
控制器
public ActionResult Index()
{
var nationalities = new List<Nationality>
{
new Nationality{Id = 0, Name = "CHOOSE NATIONALITY..."},
new Nationality{Id = 1, Name = "POLAND"},
new Nationality{Id = 2, Name = "USA"},
new Nationality{Id = 3, Name = "CANADA"}
};
var Nationalities = new SelectList(nationalities, "Id", "Name");
var persons = new List<PersonViewModel>
{
new PersonViewModel{Id = 1, LastName = "KOWALSKI", NationalityId = 1},
new PersonViewModel{Id = 1, LastName = "SMITH", NationalityId = 2},
new PersonViewModel{Id = 1, LastName = "SCHERBATSKY", NationalityId = 3}
};
ViewBag.Nationalities = Nationalities;
return View(persons);
}
查看
@model List<PersonViewModel>
@Html.EditorFor(m=> Model[0].LastName)
@Html.DropDownListFor(m => Model[0].NationalityId, (SelectList)ViewBag.Nationalities)
@Html.EditorFor(m => Model[1].LastName)
@Html.DropDownListFor(m => Model[1].NationalityId, (SelectList)ViewBag.Nationalities)
@Html.EditorFor(m => Model[2].LastName)
@Html.DropDownListFor(m => Model[2].NationalityId, (SelectList)ViewBag.Nationalities)
任何人都可以告訴我爲什麼NationalityId屬性不綁定以及
我無法上傳圖片,但它根本沒有任何約束力。每個DropDownList都有'選擇國籍...'。
謝謝,這解決了我的問題。 – 2014-10-17 13:03:37