2012-10-19 32 views
5

我有一個顯示項目列表的ASP.NET MVC應用程序。在我看來,頁面我遍歷所有的項目和渲染局部視圖中的每個項目,像這樣:Html.HiddenFor綁定到錯誤的元素

@foreach(var item in Model.items) 
{ 
    <li> 
     @Html.Partial("ItemView", item) 
    </li> 
} 

在項目視圖,我換用具有「刪除」按鈕,這樣的形式,每個項目:

@using(Html.BeginForm(...)) 
{ 
    @Html.HiddenFor(m=>m.Id) 
    <label>@Model.Name (@Model.Id)</label> 
    <input type="submit" value="Delete"/> 
} 

的項目可以正確地呈現,產生的頁面具有所有顯示其應有的名稱和ID項目的一個很好的列表。

編輯:同樣的情況發生在@隱藏,顯然,違揹我之前寫的。

此外,這隻發生在第二次呈現表單(即單擊刪除按鈕之一後),第一次一切工作正常。我的操作方法如下所示:

public ActionResult AllItems() 
{ 
    var model = new AllItemsModel(); 
    return PartialView(model); 
} 

public ActionResult Delete(DeleteModel model) 
{ 
    .... Perform the delete ... 
    return PartialView("AllItems", new AllItemsModel()); 
} 

爲什麼會發生這種情況?

回答

8

我懷疑,這是因爲你已經在你的RouteData一個 Id參數:

public ActionResult SomeAction(int id) 
{ 
    var model = ... 
    return View(model); 
} 

和您請求的頁面與/somecontroller/someaction/123。 HiddenFor幫助器現在使用路徑值中的Id而不是項目的ID。嘗試將項目視圖模型上的屬性重命名爲與id不同的內容。例如ItemId

另一種可能性是,問題只發生在回發後,而不是頁面最初呈現時。顯示你的POST動作可能有助於進一步探索這種可能性。


UPDATE:

好了,現在你已經證明你的POST操作的東西更清楚:

public ActionResult Delete(DeleteModel model) 
{ 
    .... Perform the delete ... 
    return PartialView("AllItems", new AllItemsModel()); 
} 

你基本上是在這裏創建一個新的視圖模型並將其傳遞到局部視圖。但是,綁定時,HTML助手總是使用來自ModelState的值。只有在你的視圖模型的價值。因此,如果您打算在您的POST動作中修改模型的屬性,請確保您先從ModelState中移除此值。在你的榜樣,因爲你已經完全劃傷整個視圖模式(通過創建一個new AllItemsModel()),你可以清除所有的ModelState:

public ActionResult Delete(DeleteModel model) 
{ 
    .... Perform the delete ... 

    // Clear the modelstate otherwise the view will use the values that were initially posted 
    // and not the values from your view model 
    ModelState.Clear(); 
    return PartialView("AllItems", new AllItemsModel()); 
} 

此行爲是設計,適用於所有HTML輔助,不僅HiddenFor幫手。

+0

哇,優秀的觀察。我會檢查,我想我沒有。 – zmbq

+0

你的第一個建議不正確,但你的第二個建議看起來很有希望。太糟糕了,我不能+1兩次...我會檢查它。 – zmbq

+0

是的,就是這樣。非常感謝! – zmbq