【发布时间】:2013-07-03 07:30:51
【问题描述】:
我正在编写一个显示经理列表的视图。经理在他们的名字旁边有复选框来选择他们从经理列表中删除。我在将表单提交绑定回我的视图模型时遇到问题。页面如下所示:
这是页面的 ViewModel。
public class AddListManagersViewModel
{
public List<DeleteableManagerViewModel> CurrentManagers;
}
这里是每个 DeleteableManagers 的子 ViewModel:
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>
这是我为 DeleteableManagerViewModel 创建的 EditorTemplate:
@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 但我一定遗漏了一些东西......
感谢您的帮助!
【问题讨论】:
-
Firebug 是否显示任何正在发布的内容?您是否尝试过添加 Glimpse(它可以让您跟踪绑定过程)?
-
it appears to be posted properly: __RequestVerificationToken=H7L_Uq6ie_6XAoYFhJQhQe2cuFdJzapaf8ZlgpnEVeUs3kr8kCu7wuVAjZ9ADXzsDZiKmHyqYLkdbVtG7CmSKPqE_upz1eR0Ub0aPxem94Y1&CurrentManagers%5B0%5D.ToBeDeleted=true&CurrentManagers%5B0%5D.ToBeDeleted=false&CurrentManagers%5B0%5D.ExtId=X00405982144&CurrentManagers%5B1%5D.ToBeDeleted=false [剪辑...]
-
嗯。我能看到的唯一另一个明显(可能)的问题是,当模型绑定时,如果集合的索引被破坏(跳过一个数字),最后一个序列号之后的所有内容都会被忽略/丢弃。不过,我不认为你正在做的事情应该有这个问题。
-
如果我将类型更改为 FormCollection,它会被填充。但是我当然不想绑定到那个...
-
如果你有时间,你应该发布一个你为解决问题所做的例子——我相信有人会发现它很有用。那,你可以接受你自己的答案。
标签: c# asp.net-mvc-4 checkbox