webdad3
webdad3

Reputation: 9080

Updating my ViewModel

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?

Upvotes: 0

Views: 42

Answers (2)

Andrew
Andrew

Reputation: 375

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.

Upvotes: 1

JC Lizard
JC Lizard

Reputation: 1056

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.

Upvotes: 0

Related Questions