Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Radiobuttons instead of dropdownlist in mvc 3 application?

I have a View where the model has a collection of items. Then I have an EditorFor template that takes care of creating a dropdownlist for the user to select one of a limited number of values for each item in the collection:

@model Consultants.Models.ProgramSkill
<tr>
    <td>@Model.Program.Name
    </td>
        <td>@Model.Program.Category
    </td>
    <td>
        @Html.DropDownListFor( model => model.Level, new SelectList(new[] { 0, 1, 2, 3, 4, 5 }, Model.Level))
    </td>
</tr>

But I would rather have radiobuttons to do the same thing, is that possible in MVC 3? If so, how?

like image 657
Anders Avatar asked Mar 25 '11 17:03

Anders


1 Answers

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" />
}
like image 153
Darin Dimitrov Avatar answered Sep 21 '22 08:09

Darin Dimitrov