我一起使用ASP.NET MVC和ADO.NET实体框架。实体框架与强类型MVC
我希望我的视图和控制器强类型。
但我该如何处理实体关联?
下面是一个简单的例子:
一个人有一个部门。一个部门有零个或更多的人。
我的控制器通过一个Person对象的实例,所有的部门对象的视图的集合。
public class PersonController : Controller
{
...
//
// GET: /Person/Create
public ActionResult Create()
{
Person Model = new Person();
Model.Id = Guid.NewGuid();
ViewData["Departments"] = db.Department;
return View(Model);
}
...
}
我的视图有一个“部门”DropDownList与所有部门作为选项。
<% using (Html.BeginForm()) {%>
<fieldset>
<legend>Fields</legend>
<p>
<label for="Id">Id:</label>
<%= Html.TextBox("Id") %>
<%= Html.ValidationMessage("Id", "*") %>
</p>
<p>
<label for="Name">Name:</label>
<%= Html.TextBox("Name") %>
<%= Html.ValidationMessage("Name", "*") %>
</p>
<p>
<label for="Department">Family:</label>
<%= Html.DropDownList("Department", new SelectList((IEnumerable)ViewData["Departments"], "Id", "Name"))%>
<%= Html.ValidationMessage("Department", "*")%>
</p>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
<% } %>
但是,贴到控制器的Person对象任何部门和失败!
public class PersonController : Controller
{
...
//
// POST: /Person/Create
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(Person Model)
{
try
{
db.AddToPerson(Model);
db.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}
}
...
}
为什么不从DropDownList中选定的部门“部门”自动添加到模型的人吗?
如何在强类型的视图和控制器中使用ADO.NET实体框架和ASP.NET MVC?
http://stackoverflow.com/questions/922402/strongly-typed-asp-net-mvc-with -ado-net-entity-framework – 2009-05-28 18:13:50