我只是想用上面的例子來分享我的實現。我正在填充組織到數據庫中的鍵/值對中的屬性。在我的示例中,我將每個屬性都作爲一個字典中的鍵值對存儲。字典中的每個項目將包含一個字符串鍵,如「顏色」,並像DataValueField =「1」,DataTextField =「黑」等等
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"));
}
}
查看值MultiSelectList標記
<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();
}
需要如何在控制器的組?如果您剛剛從表單中收到組ID,這足夠了嗎? – 2010-03-04 06:24:12
我只需要知道選擇是否已經改變(即提交表單時檢查哪些選項)。 但更重要的是如何呈現的複選框 – Aximili 2010-03-04 06:30:41