2012-03-19 53 views
0

我有两个相关的波苏斯DropDownListFor和TryUpdateModel在ASP.NET MVC

public class Parent 
{ 
    public Guid Id {get; set;} 
    public IList<Child> ChildProperty {get; set;} 
} 

public class Child 
{ 
    public Guid Id {get; set;} 
    public String Name {get; set;} 
} 

和我有

<div> 
    @{ 
     var children = 
      new SelectList(Child.FindAll(), "Id", "Name").ToList(); 
    } 
    @Html.LabelFor(m => m.Child) 
    @Html.DropDownListFor(m => m.Child.Id, , children, "None/Unknown") 
</div> 

一.cshtml Razor视图我想要做我的控制器以下类别:

[HttpPost] 
public ActionResult Create(Parent parent) 
{ 
    if (TryUpdateModel(parent)) 
    { 
     asset.Save(); 
     return RedirectToAction("Index", "Parent"); 
    } 

    return View(parent); 
} 

这样,如果用户选择“无/未知”,则控制器中父对象的子值为nu但如果用户选择任何其他值(即,从数据库中检索到的子对象的ID),父对象的子值被实例化并填充该ID。

基本上我与如何坚持跨越HTTP无状态的边界可能的实体,使得实体的一个正确水化,并通过默认的模型粘合剂分配名单中挣扎。我只是要求太多?

回答

1

我只是要求太多?

是的,你要求太多。

所有与POST请求一起发送的是所选实体的ID。不要指望得到更多。如果你想补充水分或任何你应该查询你的数据库。与您在GET操作中填充子集合的方式相同。

哦,并且您的POST操作存在问题=>您正在调用默认模型绑定两次。

这里有2种可能的模式(我个人更喜欢第一个,但第二个可能是在某些情况下也是有用的,当你想手动调用默认的模型粘合剂):

[HttpPost] 
public ActionResult Create(Parent parent) 
{ 
    if (ModelState.IsValid) 
    { 
     // The model is valid 
     asset.Save(); 
     return RedirectToAction("Index", "Parent"); 
    } 

    // the model is invalid => we must redisplay the same view. 
    // but for this we obviously must fill the child collection 
    // which is used in the dropdown list 
    parent.ChildProperty = RehydrateTheSameWayYouDidInYourGetAction(); 
    return View(parent); 
} 

或:

​​

在你的代码所做的其中两个是错误的一些组合。你基本上是调用默认的模型绑定两次。

相关问题