2012-03-19 56 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); 
} 

或:

​​

在你的代碼所做的其中兩個是錯誤的一些組合。你基本上是調用默認的模型綁定兩次。

相關問題