All radio buttons are grouped together for all the items in the model list

£可爱£侵袭症+ 提交于 2019-12-13 20:03:29

问题


I am using MVC5

Situation: my view iterates through a list of Person class where the properties are as follow:

int Id
string Name
string City
string ChosenText
List<string> SomeTextList

This list of string would be randomly generated strings.

while iterating through the list all the SomeTextList should be shown as radio button. Hence for every person all there are:

  • one textbox for name
  • one textbox for City
  • group of radio button for SomeTextList

The code is :

@foreach (var item in Model)
{
    @Html.EditorFor(modelItem => item.Name)
    <br />
    @Html.EditorFor(modelItem => item.Name) 
    @foreach (var ans in item.SomeTextList)
    {
        @Html.RadioButtonFor(modelItem => item.ChosenText, "ans")@Html.Label(ans)
    }
}

Issue: For all the persons the radio buttons as one group, i.e., I can select only one free text radio button from all the person list.

Goal: For every Person I should be able to select one radio button.


回答1:


You need to use a for loop to generate controls in a collection (not a foreach loop which generates duplicate name and ID attributes and would not post back to a collection)

Because every radio button you are generating the same name attribute <input type="radio" name="ChosenText" ... /> they all belong to the same group allowing only one to be selected.

for(int i = 0; i < Model.Count; i++)
{
  @Html.EditorFor(m => m[i].Name)
  <br />
  @Html.EditorFor(m => m[i].City) 
  @foreach (var ans in Model[i].SomeTextList)
  {
    <label>
      @Html.RadioButtonFor(m => m[i].ChosenText, ans)
      <span>@ans</span>
    </label>
  }
}

This will generate (for the radio buttons)

<input type="radio" name="[0].ChosenText" value="abc" />
<input type="radio" name="[0].ChosenText" value="xyz" />
.....
<input type="radio" name="[1].ChosenText" value="abc" />
<input type="radio" name="[1].ChosenText" value="xyz" />


来源:https://stackoverflow.com/questions/28261429/all-radio-buttons-are-grouped-together-for-all-the-items-in-the-model-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!