我正在寫一個顯示管理器的列表視圖。管理員在他們的名字旁邊有複選框,以選擇他們從經理列表中刪除。我遇到了將表單提交重新綁定到我的視圖模型的問題。下面是頁面的樣子:無法綁定MVC模型的POST
這裏的視圖模型的頁面。
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但我必須失去了一些東西....
感謝您的幫助!
不螢火蟲說明了什麼被張貼?你有沒有嘗試添加Glimpse(它可以讓你跟蹤綁定過程)?它似乎 –
要正確貼:__RequestVerificationToken = H7L_Uq6ie_6XAoYFhJQhQe2cuFdJzapaf8ZlgpnEVeUs3kr8kCu7wuVAjZ9ADXzsDZiKmHyqYLkdbVtG7CmSKPqE_upz1eR0Ub0aPxem94Y1&CurrentManagers%5B0%5D.ToBeDeleted =真CurrentManagers%5B0%5D.ToBeDeleted =假CurrentManagers%5B0%5D.ExtId = X00405982144&CurrentManagers%5B1%5D.ToBeDeleted =假[剪斷...] – solidau
嗯。我能看到的唯一另外一個明顯的(可能的)問題是,當模型綁定時,如果集合的索引被打破(跳過一個數字),最後一個序號後的所有內容都會被忽略/丟棄。不過,我不明白你在做什麼應該會有這個問題。 –