我有一个对象(Object1),它包含一个子对象(Child)。因此,您将通过Object1.Child访问子项。在我的ASP.NET MVC2项目中,我收到了对create方法的POST回复。 FormCollection包含Object1和Child对象的属性。我似乎无法使用“TryUpdateModel”函数更新子对象。
[HttpPost]
public ActionResult Create(FormCollection collection)
{
Object1 obj = new Object1();
obj.Child = new Child();
if (TryUpdateModel<Object1>(obj, "Object1", new[] { "ObjectName", "Child.ChildName" }))
{
// At this point, "ObjectName" is filled in, but "Child.ChildName" is not.
context.Object1s.AddObject(obj);
context.SaveChanges();
return RedirectToAction("Index");
}
return View(new Object1_ViewModel(obj));
}
感谢任何帮助。
答案 0 :(得分:1)
如果您有强类型视图,可以尝试执行类似
的操作public ActionResult Create(Object1 obj)
如果默认模型绑定器将携带任何子对象,我不肯定。如果这不起作用,您可能需要滚动自己的Model Binder。请参阅以下链接,了解如何编写一个:
http://www.codethinked.com/post/2009/01/08/ASPNET-MVC-Think-Before-You-Bind.aspx
http://www.codethinked.com/post/2010/04/12/Easy-And-Safe-Model-Binding-In-ASPNET-MVC.aspx
ASP.NET MVC2 - Custom Model Binder Examples
http://codeisvalue.wordpress.com/2010/02/10/customizing-model-binder-in-asp-net-mvc/