我一起使用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