2013-11-02 65 views
1

我有一个复杂的需求来创建动态单选按钮。如何在mvc剃须刀中创建动态单选按钮

理论是你有类别,这些类别有项目。 类别是动态的,它们的项目也是动态的。

在我的模型中我有...

public IList> ItemCategories {get;组; }

但我不确定这是如何创建radioFor按钮的正确方法?

有帮助吗?

我最初的想法是......

//型号

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 }) 
} 

//编辑

@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>    

回答

2

试试这个

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

} 

此处文本是单选按钮的文本。

+0

嗨,如果单选按钮是在一个表内并动态添加的,如何确保它在表单POST上提交。我跟着你的样品,这是有效的。但是,如果我克隆一行并添加到表中,并生成id,则无法将动态添加的VALUE POST为false或true – transformer

+0

@transformer:对于迟到回复对不起,其背后的原因是当您添加新控件时索引应该按顺序排列。例如:'model.DynamicCategories [0],model.DynamicCategories [1]'等等 当你纠正序列时,你将开始获得响应。 –

+0

爱你的头像!顺便说一句,你可以告诉我如何在动态添加/附加行 – transformer