在MVC3裡只有RadioButton,沒有RadioButtonList,但項目中又要用到,怎麼辦?
答案:自己看著辦。
實現後的功能:有一個檔案保密等級,如絕密、機密、一般等,需要在頁面中顯示,並且可以後台控制哪個被選中。
實現步驟如下:
1,將保密等級及是否選中,載入到一個List中。
View Code
List<KeyValuePair<string, bool>> secrecyList = new List<KeyValuePair<string, bool>>(); var secrecyLevelList = baseTypeDetailRepository.GetBaseTypeDetailList(BaseType.SecrecyLevel); foreach (var item in secrecyLevelList) { if (auth.SecrecyLevel == item.Caption) { secrecyList.Add(new KeyValuePair<string, bool>(item.Caption, true)); } else { secrecyList.Add(new KeyValuePair<string, bool>(item.Caption, false)); } }
2,在頁面中遍曆List,判斷是否選中,並輸入為RadioButton
View Code
@if (ViewBag.SecrecyList != null) { foreach (KeyValuePair<string, bool> item in ViewBag.SecrecyList) { if (item.Value) { @Html.RadioButton("SecrecyLevel", item.Key, new { @id = item.Key, @checked = true }) <span> @item.Key </span> } else { @Html.RadioButton("SecrecyLevel", item.Key, new { @id = item.Key }) <span> @item.Key </span> } } }
3,後台可接收選中檔案保密等級。
var secrecyLevel = collection["SecrecyLevel"];