C# 如何使用TextBoxFor更新关系的多方
假设我传入了一个带有多个地址的PERSON记录的viewmodel 我想写一个类似这样的视图(简化)C# 如何使用TextBoxFor更新关系的多方,c#,asp.net-mvc,entity-framework,asp.net-mvc-2,C#,Asp.net Mvc,Entity Framework,Asp.net Mvc 2,假设我传入了一个带有多个地址的PERSON记录的viewmodel 我想写一个类似这样的视图(简化) 我猜我做得不对:任何线索都将不胜感激 您可以使用编辑器模板 控制器: public ActionResult Index() { var model = new MyViewModel(); model.PERSON = FetchPerson(); return View(model); } [HttpPost] public ActionResult Edit(My
我猜我做得不对:任何线索都将不胜感激 您可以使用编辑器模板 控制器:
public ActionResult Index()
{
var model = new MyViewModel();
model.PERSON = FetchPerson();
return View(model);
}
[HttpPost]
public ActionResult Edit(MyViewModel model)
{
_MyRepository.Save(model);
return View(model);
}
视图:
这几乎是正确的。我认为您的第一个操作结果应该是Edit()?这样,我得到的控件具有合理的名称-PERSON.ADDRESSES[1]。Street,但在尝试保存时,我得到一个错误System.InvalidOperationException未经用户代码消息处理=EntityCollection已初始化。在反序列化对象图期间,仅应调用InitializeRelatedCollection方法来初始化新的EntityCollection。(来自myModel.Designer.cs EntityCollectionADDRESSES setter)我的错误也在stackoverflow.com/questions/1064998/…我有一个类似的viewmodel,带有实体图和一些下拉列表。可悲的是,所有发布的解决方案似乎都不起作用(对我或OP而言)
[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
MyViewModel viewmodel = GenerateViewModel(id);
try
{
UpdateModel(viewmodel);
_MyRepository.Save();
return View(viewmodel);
}
catch
{
return View(viewmodel);
}
}
public ActionResult Index()
{
var model = new MyViewModel();
model.PERSON = FetchPerson();
return View(model);
}
[HttpPost]
public ActionResult Edit(MyViewModel model)
{
_MyRepository.Save(model);
return View(model);
}
<ul>
<%: Html.EditorFor(x => x.PERSON.ADDRESSES) %>
</ul>
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<SomeNs.ADDRESS>" %>
<li>
Street: <%: Html.EditorFor(x => x.Street) %>
</li>