How to pass List to controller in MVC 4

前端 未结 1 988
遇见更好的自我
遇见更好的自我 2021-01-28 00:31

I have 2 model : Question and Answer such as below, I want to send a List model to View, and when submit form, i submit List model to controller, but in Action UpdateQuestion a

相关标签:
1条回答
  • 2021-01-28 00:59

    There are multiple issues with you code. First you cannot bind a radio button to a complex object (in your case Answer because a radio button group only posts back a single value (in your case the id value of the selected Answer). Next you loops are generating radio buttons groups that would be attempting to bind the selected answer to only the first answer which makes no sense (your setting the value of j to 0 each time). Your model needs a property to bind to (say) int SelectedAnswer.

    Start by creating view models that represent what you want to display/edit in your view (add display and validation attributes as required)

    public class AnswerVM
    {
      public int ID { get; set; }
      public string Content { get; set; }
    }
    public class QuestionVM
    {
      public int ID { get; set; }
      public string Brief { get; set; }
      public int SelectedAnswer { get; set; }
      public IEnumerable<AnswerVM> PossibleAnswers { get; set; }
    }
    

    In your get method, get your data models and map then to the view models and return IEnumerable<QuestionVM> to the view.

    Next create an EditorTemplate for typeof QuestionVM (/Views/Shared/EditorTemplates/QuestionVM.cshtml)

    @model QuestionVM
    <li>
      @Html.HiddenFor(m => m.ID)
      @Html.DisplayFor(m => m.Brief)
      <ul>
        @foreach(var answer in Model.PossibleAnswers)
        {
          <li>
            <label>
              @Html.RadioButtonFor(m => m.SelectedAnswer, answer.ID, new { id = "" })
              <span>@answer.Content</span>
            </label>
          </li>
        }
      </ul>
    </li>
    

    and in the main view

    @model IEnumerable<QuestionVM>
    ....
    @Html.BeginForm(...))
    {
      <ul>
        @Html.EditorFor(m => m) // this will generate the correct html for each question in the collection
      </ul>
      <div class="aq-button-panel">
        <button type="submit" ... />
        ...
      </div>
    }
    

    and change the POST method to

    [HttpPost]
    public ActionResult UpdateQuestion(string submit, IEnumerable<QuestionVM> model)
    

    The model now contains the ID of each question and the ID of the selected answer for each question.

    Note that if you need to return the view because ModelState is invalid, you will need to repopulate the PossibleAnswers property of each question (your not generating a form control for each property of each Answer in each Question - and nor should you) so the PossibleAnswers property will be an empty collection when you submit the form)

    0 讨论(0)
提交回复
热议问题