Radiobuttons instead of dropdownlist in mvc 3 application? Radiobuttons instead of dropdownlist in mvc 3 application? asp.net asp.net

Radiobuttons instead of dropdownlist in mvc 3 application?


That would be a perfect candidate for a custom html helper:

using System.Web.Mvc;using System.Web.Mvc.Html;using System.Text;using System.Collections.Generic;using System.Linq.Expressions;using System;public static class HtmlExtensions{    public static MvcHtmlString RadioButtonListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> ex, IEnumerable<SelectListItem> values)    {        string name = ExpressionHelper.GetExpressionText(ex);        var sb = new StringBuilder();        int counter = 1;        foreach (var item in values)        {            sb.Append(htmlHelper.RadioButtonFor(ex, item.Value, new { id = name + counter.ToString()}));            var label = new TagBuilder("label");            label.SetInnerText(item.Text);            label.Attributes.Add("for", name + counter.ToString());            sb.Append(label.ToString());            counter++;        }        return MvcHtmlString.Create(sb.ToString());    }}

Model:

public class MyViewModel{    public IEnumerable<SelectListItem> Items { get; set; }    public string Level { get; set; }}

Controller:

public class HomeController : Controller{    public ActionResult Index()    {        var model = new MyViewModel        {            Level = "2",            Items = Enumerable.Range(1, 5).Select(x => new SelectListItem            {                Value = x.ToString(),                 Text = "item " + x            })        };        return View(model);    }}

and a view:

@model AppName.Models.MyViewModel@using (Html.BeginForm()){    @Html.RadioButtonListFor(x => x.Level, Model.Items)    <input type="submit" value="OK" />}


@Html.RadioButtonFor(m => m.Level, 0)@Html.RadioButtonFor(m => m.Level, 1)@Html.RadioButtonFor(m => m.Level, 2)@Html.RadioButtonFor(m => m.Level, 3)@Html.RadioButtonFor(m => m.Level, 4)@Html.RadioButtonFor(m => m.Level, 5)

or with a simple loop:

@for(int level = 0; level <= 5; level++)@Html.RadioButtonFor(m => m.Level, level)}