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

时间:2010-03-04 06:18:24

标签: asp.net-mvc asp.net-mvc-2 html-helper

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

例如。我将这样的东西传递给模型

  model.Groups = new MultiSelectList(k.Groups, "Id", "Name", selectedGroups)

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

<% 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>
<% } %>
  

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

我可以使用HTML Helper方法吗?

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

2 个答案:

答案 0 :(得分: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;

复选框元素:

<% 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>
<% } %>   

在动作中接受了一个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
    }
}

我希望能给出一些想法。

答案 1 :(得分:2)

我只想使用上面的示例分享我的实现。我正在填充在我的数据库中组织为键/值对的属性。在我的示例中,我将每个属性存储为Dictionary中的键值对。字典中的每个项目都包含一个字符串键,如“Color”和一个MultiSelectList,其值为DataValueField =“1”,DataTextField =“Black”等......

VewModel代码

public Dictionary<string, MultiSelectList> Properties { get; private set; }

    private void SetProperties()
    {
        this.Properties = new Dictionary<string, MultiSelectList>();

        foreach(InventoryItemProperty property in new InventoryItemPropertyRepository().FindAllInventoryItemProperties())
        {
            this.Properties.Add(property.Key.Name, new MultiSelectList(property.Values, "Id", "Value"));
        }
    }

查看标记

<div id="editor-inventory-item-properties">
        <% foreach(string key in Model.Properties.Keys){ %>
            <div class="editor-label">
                <label for="<%= key.ToLower() %>"><%= key %></label><br />
                <% foreach(var item in Model.Properties[key]){ %>
                    <input type="checkbox" 
                        id="<%= key.ToLower() + "-" + item.Text.ToLower() %>" 
                        name="inventoryItemPropertyValues" 
                        value="<%= item.Value %>" 
                        <%= item.Selected ? "checked=\"checked\"" : string.Empty %> />
                    <label for="<%= key.ToLower() + "-" + item.Text.ToLower() %>">
                    <%= item.Text %></label><br />
                <% } %>
            </div>
        <% } %>
    </div>

控制器操作代码

//
    // POST: /Admin/InventoryItems/Create

    [HttpPost]
    public ActionResult Create(InventoryItem inventoryItem, int[] inventoryItemPropertyValues)
    {
        try
        {
            inventoryItem.Created = DateTime.Now;
            inventoryItem.LastUpdated = inventoryItem.Created;
            this.inventoryItemRepository.Add(inventoryItem);
            this.inventoryItemRepository.Save();

            if(inventoryItemPropertyValues != null)
            {
                SaveInventoryItemPropertyValues(inventoryItem.Id, inventoryItemPropertyValues);
            }

            return RedirectToAction("Details", new { id = inventoryItem.Id });
        }
        catch
        {
            throw;
            //return View();
        }
    }
private void SaveInventoryItemPropertyValues(int inventoryItemId, int[] inventoryItemPropertyValues)
    {
        for(int i = 0; i < inventoryItemPropertyValues.Length; i++)
        {
            this.inventory_Item_ProperytValueRepository.Add(new Inventory_Item_PropertyValue() { InventoryItemId = inventoryItemId, InventoryItemPropertyValueId = inventoryItemPropertyValues[i] });
        }

        this.inventory_Item_ProperytValueRepository.Save();
    }