How to get value of a Radiobuttonfor(created using

2019-09-20 18:19发布

问题:

VIEW

the increment does not work

int i = 0; 
foreach (var x in Model)
{
<div>

      @if(x.MCchoices.Any())
      {
          foreach (var item in x.MCchoices)
          {
             @item.question_desc
            foreach(var choices in item.MCchoices)
            {
                   @Html.RadioButtonFor(model => choices.qc_selectedchoice, choices.qc_id)
                   @Html.DisplayFor(model => choices.qc_choice)
            }
          }
      }
@{i++;}
</div>

Whenever i debug i can't get the value of the radiobutton to my controller

MODEL

public class QuizMaker
{
   public string question_desc { get; set; }
    public string question_id { get; set; }
    public string qc_choice { get; set; }
    public string qc_id { get; set; }
    public string qc_selectedchoice { get; set; }

   public IEnumerable<QuizMaker> MCchoices { get; set; } }

i can't get the value on post:( help is so much appreicated :))))

回答1:

Don't use foreach it brokes model binding like Stephen Muekle said.

You should either define EditorTemplate for each model. Or use for loop:

for (int i = 0; i < Model.Count(); i++)
{
<div>

      @if(Model[i].MCchoices.Any())
      {
          for (int j = 0; j < Model[i].MCchoices.Count(); j++)
          {
            @Model[i].MCchoices[j].question_desc
            for (int t = 0; t < Model[i].MCchoices[j].Count(); t++)
            {
                   @Html.RadioButtonFor(model => Model[i].MCchoices[j].MCchoices[k].qc_selectedchoice, Model[i].MCchoices[j].MCchoices[k].qc_id)
                   @Html.DisplayFor(model => Model[i].MCchoices[j].MCchoices[k].qc_choice)
            }
          }
      }
</div>

I can be wrong with indexes couse i don't understand why you using 2 nested foreach for MCchoices collection. But i hope you get the idea.