问题描述:

I have a ViewModel that is something very similar to this:

 public List<Question> Questions { get; set; }

public List<QuestionAnswer> QuestionAnswers { get; set; }

I populate the lists in the Controller and I pass the ViewModel to the View. Everything works great. However, my View is updatable (Read/Write).

I'm wondering is this the best way to accomplish this? What is the best way to update my QuestionAnswers?

Do I loop the form collection or is there a better way of doing this?

网友答案:

Generate your razor view like so:

@using (Html.BeginForm("MyPostAction", "MyController", FormMethod.Post))
{
        @for (int i = 0; i < Model.QuestionAnswers.Count; i++)
        {           
          @Html.TextBoxFor(m => m.QuestionAnswers[i].Answer)
        }
}

Then in your MyPostAction catch the submitted results

[HttpPost]
public ActionResult MyPostAction(List<QuestionAnswer> QuestionAnswers)
{
     foreach (var questionAnswer in QuestionAnswers)
     {
           // Do your DB update here
     }

     return View();
}

If you need to update both questions and questionAnswer lists in the same post action you can pass in two list collections as arguments.

网友答案:

In terms of best practices I would say you have a good approach but in terms of architecture, you would be better off putting the answer collection within the question itself.

相关阅读:
Top