2013-11-02 66 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