how to create dynamic radio buttons in mvc razor

2020-04-21 06:16发布

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>              

1条回答
戒情不戒烟
2楼-- · 2020-04-21 06:48

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.

查看更多
登录 后发表回答