I just wanted to share my implementation using the example from above. I'm populating properties that are organized into key / value pairs in my database. In my example I store each property as a key value pair in a Dictionary. Each item in the Dictionary will contain a string key such as "Color" and a MultiSelectList with values like DataValueField="1", DataTextField="Black" etc...
VewModel Code
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
<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>
Controller Action code
//
// 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();
}