I m stumped with a problem in ASP.NET MVC 3 - handling editing and updating of a master-detail relationship from a single MVC view.
I m using Entity Framework 4.2 code-first to build a small app. It uses a Person
class (which has Name
, FirstName
and so on), and an Address
class (with Street
, Zipcode
, City
etc.).
These two classes have a m:n relationship to one another, modelled in EF code-first with:
public class Person
{
private List<Address> _addresses;
// bunch of scalar properties like ID, name, firstname
public virtual List<Address> Addresses
{
get { return _addresses; }
set { _addresses = value; }
}
}
public class Address
{
private List<Person> _people;
// bunch of scalar properties like AddressID, street, zip, city
public virtual List<Person> People
{
get { return _people; }
set { _people = value; }
}
}
我用一些数据人工填充数据库,用EF4.2进行细微工作,检索数据。
我有一个伙伴关系。 NET MVC PersonController
,其中我装上了Person
,包括其所有现有地址,并用Razor的观点显示。 d 允许用户改变或更新现有地址,并删除或插入地址。 管制人员从妇女和家庭服务处获得有关该人士的数据:
public ActionResult Edit(int id)
{
Person person = _service.GetPerson(id);
return View(person);
}
在回程时适当填满个人地址。
对这一作品的细表——它显示了预期的<代码>Person的所有数据。
@model DomainModel.Person
<h2>Edit</h2>
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>Person</legend>
@Html.HiddenFor(model => model.PersonId)
<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
.... and a few more of those scalar properties being edited....
<hr/>
<h4>Addresses</h4>
@foreach (var item in Model.Addresses)
{
<tr>
<td>
@Html.EditorFor(modelItem => item.Street)
</td>
<td>
@Html.EditorFor(modelItem => item.ZipCode)
</td>
<td>
@Html.EditorFor(modelItem => item.City)
</td>
</tr>
}
<hr/>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
然而,当Im试图在挽救被编辑的人时处理《持久性有机污染物手册》时,我看不到所展示的(可能经过编辑的)地址:
[HttpPost]
public ActionResult Edit(Person person)
{
if (ModelState.IsValid)
{
_service.UpdatePerson(person);
return RedirectToAction("Index");
}
return View(person);
}
The person.Addresses
property is always null in this case. Hmmm.... what am I missing?? How can I edit a Person-to-Addresses relationship on an ASP.NET MVC view, and get back the Person
AND its associated Addresses
from my view, so I can pass them to EF to save them back to the database tables??