2013-07-02 53 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