填充RadioButton

时间:2015-05-18 11:32:34

标签: c# html

我有一个名为[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;
}

我想基于此List填充我的RadioButton ..

在我的控制器中:

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

在我看来:

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

它没有工作..(我用DropDown测试并且工作得很好),是不是可以使用RadioButton?

修改

我试过了:

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

看起来很有效,但我可以在哪里放置无线电按钮的名称?

2 个答案:

答案 0 :(得分:0)

您还可以遍历列表并根据您拥有的数据更改下面的代码。

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

答案 1 :(得分: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