Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

asp.net mvc 3 - How can I create a RadioButtonList in a MVC View via HTML class ( Razor syntax )

I need to show my list in a RadioButtonList , some thing like this: @Html.RadioButtonList("FeatureList", new SelectList(ViewBag.Features)) But as you know there is no RadioButtonList class in HTML Helper class and when I use : @Html.RadioButton("FeatureList", new SelectList(ViewBag.Features)) it shows me a blank list! // Controller codes :

 public ActionResult Rules()
        {

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

        }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Html.RadioButton does not take (string, SelectList) arguments, so I suppose the blank list is expected ;)

You could 1)

Use a foreach over your radio button values in your model and use the Html.RadioButton(string, Object) overload to iterate your values

// 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)
}

or 2)

Write your own helper method for the list--might look something like this (I've never written one like this, so your mileage may vary)

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());
}

And then call your new helper in your view like (assuming Model.Options is still List or other appropriate data type)

@Html.RadioButtonList("nameOfList", Model.Options)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...