ASP.NET MVC:从MultiSelectList渲染复选框列表

Axi*_*ili 9 asp.net-mvc html-helper asp.net-mvc-2

如何将MultiSelectList与复选框列表相关联?

例如.我把这样的东西传给了模特

  model.Groups = new MultiSelectList(k.Groups, "Id", "Name", selectedGroups)
Run Code Online (Sandbox Code Playgroud)

我应该如何呈现它?这不起作用

<% foreach (var item in Model.Groups.Items) { %>
  <input type="checkbox" name="groups" value="<%=item.Value%>" id="group<%=item.Value%>" checked="<%=item.Selected?"yes":"no"%>" />
  <label for="group<%=item.Value%>"><%=item.Text%></label>
<% } %>
Run Code Online (Sandbox Code Playgroud)

错误CS1061:'object'不包含'Value'的定义...

我可以使用HTML Helper方法吗?

(然后,除非它很简单,否则在提交表单时我应该如何在Controller上获取所选值?)

Çağ*_*kin 18

我刚试过看看我们如何看待选择是否改变了.

public class Group {
    public int ID { get; set; }
    public string Name { get; set; }
}

//And some data to play with
var allGroups = new List<Group>();
allGroups.Add(new Group { ID = 1, Name = "one" });
allGroups.Add(new Group { ID = 2, Name = "two" });
allGroups.Add(new Group { ID = 3, Name = "three" });

var selectedGroups = new List<Group>();
selectedGroups.Add(allGroups[0]);
selectedGroups.Add(allGroups[2]);

var m = new MultiSelectList(allGroups, "ID", "Name", 
    selectedGroups.Select(x => x.ID));

//passed that data to the view with ViewData
ViewData["list"] = m;
Run Code Online (Sandbox Code Playgroud)

复选框元素:

<% foreach (var item in (MultiSelectList)ViewData["list"]) { %>
    <input type="checkbox" name="groups" value="<%=item.Value%>"
        id="group<%=item.Value%>"
        <%=item.Selected ? "checked=\"checked\"" : String.Empty%>/>
    <label for="group<%=item.Value%>"><%=item.Text%></label>
<% } %>   
Run Code Online (Sandbox Code Playgroud)

在动作中接受一个int数组:

[HttpPost]
public ActionResult SomeAction(int[] groups) {
    if (groups != null) {
        var postedSelection = allGroups.Where(x => groups.Contains(x.ID));
        if (!selectedGroups.SequenceEqual(postedSelection)) {
            //selection was changed
        }
        else {
            //selection is the same
        }
    }
    else {
        //no group ID was posted
    }
}
Run Code Online (Sandbox Code Playgroud)

我希望能给出一些想法.