假设您有一个名为 ActionType 的模型:
public class ActionType
{
public int ActionTypeID { get; set; }
...
}
由于您的 SelectList 使用相同的属性名称,因此 ModelBinder 将负责设置正确的 POSTed 值:
new SelectList(query.AsEnumerable(), "ActionTypeID", "ActionTypeTitle");
--------------------------------------------^
只需记住将同名的属性添加到您在 Action 中使用的 Model 类:
-------------------------------v Add the property to this class.
[HttpPost]
public ActionResult Create(SomeModel model)
{
}
这是一个例子。想象一下,您有以下实体框架已经生成的实体:
Person Country
------- -------
PersonID CountryID
FullName Name
CountryID
[HttpPost]
public ActionResult Create(PersonModel model)
{
if (ModelState.IsValid)
{
DbEntities db = new DbEntities();
Person person = new Person();
person.FullName = model.FullName;
person.CountryID = model.CountryID; // This value is from the DropDownList.
db.AddToPersons(person);
db.SaveChanges();
return RedirectToAction("Index", "Home");
}
// Something went wrong. Redisplay form.
return View(model);
}
只需将 POSTed ID 值设置为实体对象的外键属性即可。