I want to display under each name from the table radio group relating to this name.
Now, I slightly modified Lanceley’s example (
http://jonlanceley.blogspot.ru/2011/06/mvc3-radiobuttonlist-helper.html[
^]). But I have to pre-create so many special fields in model as radio units I want to display.
In other case groups are coupled.
How can I solve this problem?
From view:
@model IEnumerable<Sample.Models.IndexViewModel>
…
int i=0;
for (i = 0; i < Model.Count();i++ )
{
@Html.DisplayTextFor(m => m.ElementAt(i).Name)
@Html.RadioButtonForSelectList(m => m.ElementAt(i).TestRadio, Model.ElementAt(i).TestRadioList)
}
From model:
public class IndexViewModel
{
public IEnumerable<SelectListItem> TestRadioList { get; set; }
public String Name { get; set; }
[Required(ErrorMessage = "You must select an option for TestRadio")]
public String TestRadio { get; set; }
[Required(ErrorMessage = "You must select an option for TestRadio2")]
public String TestRadio2 { get; set; }
[Required(ErrorMessage = "You must select an option for TestRadio3")]
public String TestRadio3 { get; set; }
…
}
From helper:
public static class HtmlExtensions
{
public static MvcHtmlString RadioButtonForSelectList<TModel, TProperty>(
this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression,
IEnumerable<SelectListItem> listOfValues)
{
var metaData = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
var sb = new StringBuilder();
if (listOfValues != null)
{
foreach (SelectListItem item in listOfValues)
{
var id = string.Format("{0}_{1}", metaData.PropertyName, item.Value);
var label = htmlHelper.Label(id, HttpUtility.HtmlEncode(item.Text));
var radio = htmlHelper.RadioButtonFor(expression, item.Value, new { id = id }).ToHtmlString();
sb.AppendFormat("<div class=\"RadioButton\">{0}{1}</div>", radio, label);
i++;
}
}