1

Currently I am able to dynamically populate @Html.DropDownList() from a dataset. The code below works fine for this.

CONTROLLER

public static IEnumerable<SelectListItem> myList
    {
        get
        {
            ReportAPI.ReportsAPI ws = new ReportAPI.ReportsAPI();
            DataSet ds = ws.GetReportDataSet(userguid, reportguid);
            DataTable dt = ds.Tables[0];

            List<SelectListItem> list = new List<SelectListItem>();
            foreach (DataRow dr in dt.Rows)
            {
                list.Add(new SelectListItem
                {
                    Text = dr["text"].ToString(),
                    Value = dr["value"].ToString(),
                });
            }
            return list;
        }
    }

public ActionResult NewSubscriber()
    {

        ViewData["subscriptionplanx"] = myList;

        return View();
    }

VIEW

@Html.DropDownList("subscriptionplanx")

Now, instead of using a DropDownList, I want to use radio buttons instead. How would I do this?

Derek
  • 5,137
  • 9
  • 28
  • 39
  • 3
    There has been some work on HtmlHelpers for RadioButtonLists - here: http://jonlanceley.blogspot.com/2011/06/mvc3-radiobuttonlist-helper.html and http://stackoverflow.com/questions/2512809/has-anyone-implement-radiobuttonlistfort-for-asp-net-mvc – Ta01 Apr 23 '13 at 18:00
  • Furthermore, you should also use a "ViewModel" instead of throwing stuff into ViewData. ViewData is really awkward given its dynamic nature, and you'll have to use HiddenFields to get data back into POST actions anyway. Just create a ViewModel for the View in question, and you can eliminate all the casting hassle with ViewData. – Graham Apr 23 '13 at 20:24

1 Answers1

5

Using a HtmlHelper is probably the most elegant solution. Anyway, if you're looking for something straighforward, try this:

@foreach(SelectListItem item in (IEnumerable<SelectListItem>)ViewData["subscriptionplanx"])
{
    <input type="radio" name="subscriptionplanx" value="@item.Value" />@item.Text <br />
}
Andre Calil
  • 7,652
  • 34
  • 41
  • Ok. Your code works in Create view, But in Edit view, Radio buttons are not selected. – oneNiceFriend May 22 '16 at 06:09
  • 1
    @oneNiceFriend You mean if it should be selected based on values from the DB? `item` should have the selected state, so just use it to set the `checked=true` property of the `input` element. – Andre Calil May 22 '16 at 16:32