2015-05-18 68 views
0

我有一個名爲[SchoolingLevels]類,使用此代碼:填充單選

public List<SelectListItem> schoolingLevels = new List<SelectListItem>(); 

public List<SelectListItem> Populate() 
{ 
     schoolingLevels.Add(new SelectListItem { Text = "Primary incomplete", Value = "Primary incomplete" }); 
     schoolingLevels.Add(new SelectListItem { Text = "Primary", Value = "Primary" }); 
     schoolingLevels.Add(new SelectListItem { Text = "Secondary incomplete", Value = "Secondary incomplete" }); 
     schoolingLevels.Add(new SelectListItem { Text = "Secondary", Value = "Secondary" }); 
     schoolingLevels.Add(new SelectListItem { Text = "Higher education incomplete", Value = "Higher education incomplete" }); 
     schoolingLevels.Add(new SelectListItem { Text = "Higher education", Value = "Higher education" }); 
     schoolingLevels.Add(new SelectListItem { Text = "Post-graduation/MBA", Value = "Post-graduation/MBA" }); 
     return schoolingLevels; 
} 

而且我要在此基礎上列表來填充我的單選按鈕..

在我的控制器:

ViewBag.Scholarity = new SchoolingLevels().Populate(); 

筆者認爲:

@Html.RadioButton("Scholarity", "a") 

它不工作..(我用DropDown進行測試並完美工作),RadioButton不可能嗎?

編輯

我試了一下:

@foreach (var myValue in ViewBag.Scholarity) 
{ 
    Html.RadioButton("Scholarity","Value") 
} 

這似乎工作,但我在哪裏可以把單選按鈕的名字嗎?

Ty。

+0

它不起作用?是否有任何事情發生或者它不正確地填充? – SuperBiasedMan

+0

我不這麼認爲,因爲它的下拉工作。 – developer033

回答

0

我認爲下面的代碼將幫助您:

@foreach (var myValue in ViewBag.Scholarity) 
{ 
    string text = myValue.Text.ToString(); 
    string val = myValue.Value.ToString(); 
    @Html.RadioButton("ScholarityList", val); 
    <span>@text</span> 
} 

或像下面創建自定義的HTML幫助:

public static MvcHtmlString RadioButtonList(this HtmlHelper helper, 
string NameOfList, List<string> RadioOptions) { 

StringBuilder sb = new StringBuilder(); 

// put a similar foreach here 
foreach(var myOption in RadioOptions) { 
    sb.Append(helper.RadioButton(NameOfList, myOption)); 
} 

return new MvcHtmlString(sb.ToString()); 

}

@Html.RadioButtonList("ScholarityList", ViewBag.Scholarity); 

請遵照鏈接瞭解更多:http://www.codeproject.com/Tips/657164/Radio-Button-List-for-MVC

+0

對我來說,不存在RadioButtonList,只有RadioButton和RadioButtonFor .. 而第一個解決方案,我試過@ Html.RadioButton(「ScholarityList」,「價值」),但我不能命名單選按鈕..只出現檢查選項 – developer033

+0

@ developer033我編輯了答案。你能檢查一下嗎? – Nivs

+0

非常感謝Nivs。 我的最後的代碼: Html.RadioButton( 「Scholarity」,值,新的{ID = 「Scholarity」,@style = 「寬度:汽車;背景:無;邊界:無」}) 文本
(我不能使用「@」..) 順便說一句,有沒有在「顯示:..」的任何選項顯示其他每個單選按鈕?像重複的方向:在ASP.NET垂直?我沒有找到任何。 – developer033

0

您還可以遍歷您的列表並根據您擁有的數據更改以下代碼。

foreach (var item in Model) 
{ 
    @Html.RadioButtonFor(m => m.item, "Yes") @:Yes 
    @Html.RadioButtonFor(m => m.item, "No") @:No 
}