Asp.net-mvc – how to create dynamic radio buttons in mvc razor

asp.net-mvcasp.net-mvc-4razor

I have a complex need to create dynamic radio buttons.

The theory is you have categories and these categories have items.
The categories are dynamic and so are their items.

In my model i have…

public IList> ItemCategories { get; set; }

but I'm not sure if this is the correct way how to create the radioFor button?

help?

My initial Idea was…

//Model

public IList<Category> DynamicCategories { get; set; }

public IList<long> DynamicCategoryItems { get; set; }

//HTML

@for (int i = 0; i < Model.DynamicCategories.Count; i++)
{
      @Html.EditorFor(model => model.DynamicCategories[i], "DynamicCategories", new { Index = i, IsHidden = false })
}

//Editor

@model Category
@{
    Entities.Category rowModel = new Entities.Category();
    int count = ViewBag.Index == null ? 0 : (int)ViewBag.Index;
}

<h3>@Model.Name</h3>
<div class="options">
    @foreach (CategoryItem item in Model.CategoryItems.Where(x => x.Enabled))
    {
        <div class="option" data-search-text="@item.Name">
            @item.Name 
            <input type="radio" name="DynamicCategoryItems[@count]" value="@item.Id" @(item.Selected ? "checked" : "")/>
        </div>            
    }
    <div class="clear"></div>
</div>              

Best Answer

try this

for (int i = 0; i < Model.DynamicCategories.Count; i++)
{
    @Html.RadioButtonFor(model => model.DynamicCategories[i],model => model.DynamicCategoryItems[i]) @:Text

}

here Text is text for radiobutton.