首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何通过HTML类在MVC视图中创建RadioButtonList (Razor语法)

如何通过HTML类在MVC视图中创建RadioButtonList (Razor语法)
EN

Stack Overflow用户
提问于 2011-05-26 08:21:03
回答 1查看 37.8K关注 0票数 1

我需要在RadioButtonList中显示我的列表,就像这样:@Html.RadioButtonList("FeatureList",new SelectList(ViewBag.Features)),但是你知道在HTML Helper类中没有RadioButtonList类,当我使用:@Html.RadioButton("FeatureList",new SelectList(ViewBag.Features))时,它会显示一个空白列表!//控制器代码:

代码语言:javascript
复制
 public ActionResult Rules()
        {

            ViewBag.Features = (from m in Db.Features where m.ParentID == 3 select m.Name);
            return View();

        }
EN

回答 1

Stack Overflow用户

发布于 2011-05-26 10:28:01

Html.RadioButton不接受(string, SelectList)参数,所以我认为应该是空白列表;)

你可以1)

对模型中的单选按钮值使用foreach,并使用Html.RadioButton(string, Object)重载来迭代值

代码语言:javascript
复制
// Options could be a List<string> or other appropriate 
// data type for your Feature.Name
@foreach(var myValue in Model.Options) {
    @Html.RadioButton("nameOfList", myValue)
}

或2)

为list编写您自己的helper方法--可能是这样的(我从来没有写过这样的方法,所以您的里程可能会有所不同)

代码语言:javascript
复制
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());
}

然后在视图中调用新的助手,比如(假设Model.Options仍然是List或其他适当的数据类型)

代码语言:javascript
复制
@Html.RadioButtonList("nameOfList", Model.Options)
票数 12
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6132474

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档