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