我正在設計可以接收對象的ASP.NET MVC應用程序中的表單。下面是一個典型編輯動作的樣子:更新來自表單的LINQ模型的最佳方式
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(int id, Person person)
{
peopleService.SavePerson(person);
return Redirect("~/People/Index");
}
的SavePerson
呼叫服務做到這一點:
public void SavePerson(Person person)
{
_peopleRepository.SavePerson(person);
}
而且SavePerson
調用存儲庫中的做到這一點:
public void SavePerson(Person person)
{
using (var dc = new SIGAPDataContext())
{
if (person.IsNew)
{
dc.People.InsertOnSubmit(person);
}
else
{
dc.People.Attach(person, true);
}
dc.SubmitChanges();
}
}
現在,這在我創建新記錄時效果很好。但是,當我更新它沒有所有的表單元素時,它會刪除其他字段。例如,我的Person模型有一個NationalityID屬性,如果它沒有顯示在編輯表單上,則該屬性爲空。
什麼是最好的做法,使模型更新只是來自表單的字段?我必須首先從數據庫中的記錄和更新手動的屬性,如:
Person persistedPerson = peopleService.GetPerson(person.ID);
persistedPerson.Name = person.Name;
persistedPerson.DateOfBirth = person.DateOfBirth
// etc...
或有任何其他的,更清潔的方式做到這一點?
現在我只需要如何使用UpdateModel在窗體上使用嵌套實體。非常感謝! – changelog 2009-02-27 18:12:52