2010-03-04 28 views
8

Come si associa un MultiSelectList a un elenco di checkbox?ASP.NET MVC: elenco di caselle di controllo Render da MultiSelectList

es. Passo qualcosa del genere al modello

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

Come devo renderlo? Questo non funziona

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

Errore CS1061: 'oggetto' non contiene una definizione per 'Valore' ...

Esiste un metodo di supporto HTML che posso usare?

(Poi, a meno che non è semplice, come devo quindi ottenere i valori selezionati di nuovo sul Controller quando il modulo viene inviato?)

+0

Come avete bisogno di quei gruppi nel controllore? Sarebbe sufficiente se hai appena ricevuto gli ID di gruppo dal modulo? –

+0

Avrò solo bisogno di sapere se le selezioni sono cambiate (ad esempio, quali sono controllate quando il modulo viene inviato). Ma ancora più importante come rendere le caselle di controllo – Aximili

risposta

18

ho solo provato a vedere come possiamo vedere se la selezione è stata cambiata.

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; 

Gli elementi di caselle di controllo:

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

Accettato un array int nell'azione:

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

spero che dà un'idea.

+0

che vedo, quindi dovrebbe essere foreach (var item in Model.Groups) invece di foreach (var item in Model.Groups.Items) Grazie Cagdas ! – Aximili

2

Volevo solo condividere la mia implementazione utilizzando l'esempio di cui sopra. Sto popolando le proprietà che sono organizzate in coppie chiave/valore nel mio database. Nel mio esempio memorizzo ciascuna proprietà come una coppia di valori chiave in un dizionario. Ogni elemento nel Dizionario conterrà una chiave stringa come "Colore" e un MultiSelectList con valori come DataValueField = "1", DataTextField = "Black", ecc ...

Codice 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")); 
     } 
    } 

View markup

codice
<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> 

azione controller

// 
    // 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(); 
    } 
Problemi correlati