2013-07-02 48 views
3

我正在寫一個顯示管理器的列表視圖。管理員在他們的名字旁邊有複選框,以選擇他們從經理列表中刪除。我遇到了將表單提交重新綁定到我的視圖模型的問題。下面是頁面的樣子:無法綁定MVC模型的POST

enter image description here

這裏的視圖模型的頁面。

public class AddListManagersViewModel 
{ 
    public List<DeleteableManagerViewModel> CurrentManagers; 
} 

而這裏的子視圖模型爲每個DeleteableManagers的:

public class DeleteableManagerViewModel 
{ 
    public string ExtId { get; set; } 
    public string DisplayName { get; set; } 

    public bool ToBeDeleted { get; set; } 
} 

這是主視圖代碼:

@model MyApp.UI.ViewModels.Admin.AddListManagersViewModel 
<div class="row"> 
    <div class="span7"> 
     @using (Html.BeginForm("RemoveManagers","Admin")) 
     { 
      @Html.AntiForgeryToken() 
      <fieldset> 
       <legend>System Managers</legend> 

       <table class="table"> 
        <thead> 
         <tr> 
          <th>Name</th> 
          <th>Remove</th> 
         </tr> 
        </thead> 

        <tbody> 
         @Html.EditorFor(model => model.CurrentManagers) 
        </tbody> 
       </table> 
      </fieldset> 
      <div class="form-actions"> 
       <button type="submit" class="btn btn-primary">Delete Selected</button> 
      </div> 
     } 
    </div> 
</div> 

這是EditorTemplate我已經對於DeleteableManagerViewModel創建:

@model MyApp.UI.ViewModels.Admin.DeleteableManagerViewModel 

<tr> 
    <td>@Html.DisplayFor(model => model.DisplayName)</td> 
    <td> 
     @Html.CheckBoxFor(model => model.ToBeDeleted) 
     @Html.HiddenFor(model => model.ExtId) 
    </td> 
</tr> 

但是,當我將表單提交給控制器時,模型返回null!這就是我想做的事情:

[HttpPost] 
public virtual RedirectToRouteResult RemoveManagers(AddListManagersViewModel model) 
{ 
    foreach (var man in model.CurrentManagers) 
    { 
     if (man.ToBeDeleted) 
     { 
      db.Delete(man.ExtId); 
     }   
    } 
    return RedirectToAction("AddListManagers"); 
} 

我想沿着這個帖子下面:CheckBoxList multiple selections: difficulty in model bind back但我必須失去了一些東西....

感謝您的幫助!

+1

不螢火蟲說明了什麼被張貼?你有沒有嘗試添加Glimpse(它可以讓你跟蹤綁定過程)?它似乎 –

+0

要正確貼:__RequestVerificationToken = H7L_Uq6ie_6XAoYFhJQhQe2cuFdJzapaf8ZlgpnEVeUs3kr8kCu7wuVAjZ9ADXzsDZiKmHyqYLkdbVtG7CmSKPqE_upz1eR0Ub0aPxem94Y1&CurrentManagers%5B0%5D.ToBeDeleted =真CurrentManagers%5B0%5D.ToBeDeleted =假CurrentManagers%5B0%5D.ExtId = X00405982144&CurrentManagers%5B1%5D.ToBeDeleted =假[剪斷...] – solidau

+0

嗯。我能看到的唯一另外一個明顯的(可能的)問題是,當模型綁定時,如果集合的索引被打破(跳過一個數字),最後一個序號後的所有內容都會被忽略/丟棄。不過,我不明白你在做什麼應該會有這個問題。 –

回答

1

嗯。我認爲這最終是問題;這裏就是你冒充什麼:

CurrentManagers[0].ToB‌​eDeleted=true&CurrentManagers[0].ToBeDeleted=false&CurrentManagers[0].Ext‌​Id=X00405982144 

你的模型是一個AddListManagersViewModel具有的CurrentManagers的集合。所以,你發佈的DeleteableManagerViewModel數組,不獲取綁定到「包裝」的模式。您可以嘗試改變模型參數

params DeleteableManagerViewModel[] model

我從來沒有使用EditorFor擴展,雖然如此,我只是猜測......

+0

你正在與它沒有約束包裝模型的東西。當我將其更改爲不包含包裝時,它會正常工作並進行綁定。但問題是(我認爲)我需要包裝器,因爲頁面實際上顯示了兩種形式(另一種添加到管理器中,即使與包裝器一起工作和綁定......) – solidau