MVC4中的模型绑定多选

时间:2014-10-16 10:32:04

标签: asp.net-mvc model-binding multi-select

我的班级

public partial class Reference
    {    
        public Reference()
        {
          this.Reference1 = new HashSet<Reference>();         
        }
        public int[] Permissions{ get; set;}
        public virtual ICollection<Reference> Reference1 { get; set; }
        public int RefID { get; set; }
        public string Description { get; set; }
    }

并且查看

@using(@Html.BeginForm())
{
    @model Trials.Classes.Reference
       <table>
         <tr>
          <td colspan="2">        
             @Html.DropDownListFor(x => x.RefID, @ViewBag.role as SelectList, new { @class = "dropdown" })
          </td>    
          <tr>    
          <td colspan="2">          
             @Html.ListBoxFor(x => x.Permissions,
                        @ViewBag.permissions as MultiSelectList,
                        new { @class = "chosen-select", data_placeholder = "Choose Permissions...", style = "width:500px;", tabindex = "4" }
               )

           </td>
           </tr>
            <tr>
            <td><input type="submit" value="Save"  /></td>
            <td> <input type="button" value="Cancel" onclick="closeDialog()" /> </td>
            </tr>
        </table>
}

和控制器是

public ActionResult editPermissions(int id)
        {
            ViewBag.role = new SelectList(rep.getRoles("Roles"), "RefID", "Description");
            ViewBag.permissions = new SelectList(rep.getRoles("Perms"), "RefID", "Description");
           Reference r = db.Reference.Find(id);
          r.Permissions = r.Reference1.Select(rf => rf.RefID).ToArray();
            if (r == null)
            {
                return HttpNotFound();
            }
            else
            {
                    return PartialView("_editRole", r);
            }
        }

问题是多选列表不显示来自db的值。这个fisr下拉列表显示来自datbase的值是预选的,但是在multidropdown中它只显示为空....我想显示已经在该对象中的预选值,然后用户可以取消选择或选择更多.... 在此先感谢...

1 个答案:

答案 0 :(得分:1)

MultiSelectList接受一个参数来指示所选的值,而您不提供此参数。但是,编写的代码将使用普通的SelectList,无论如何都是从MultiSelectList派生的。因此,只需从视图中删除as MultiSelectList即可。

如果有一个原因我错过了这必须是MultiSelectList,那么你需要在你的控制器中设置所选的项目。您可以先从数据库中获取当前值,然后设置ViewBag.permissions。这看起来像是:

public ActionResult editPermissions(int id)
{
    ViewBag.role = new SelectList(rep.getRoles("Roles"), "RefID", "Description");
    Reference r = db.Reference.Find(id);
    if (r == null) return HttpNotFound();
    r.Permissions = r.Reference1.Select(rf => rf.RefID).ToArray();
    ViewBag.permissions = new MultiSelectList(rep.getRoles("Perms"), "RefID", "Description", r.Permissions);
    return PartialView("_editRole", r);
}

另请注意,目前在检查null之前在r上设置了一个值。因此,在进行空检查之前,您将有一个空引用异常。我已经重新命令你的方法来解决这个问题以及设置选定的值。