views:

162

answers:

2

I have a single model type to wrap up various models I want to use in my view:

public class QuestionViewData {
        public Question Question { get; set; }
        public IList<Answer> Answers { get; set; }
}

Now, in my question view I pull the data from the Question object - that's fine. Secondly I iterate through all Answer objects and pass them to a partial view:

<% foreach(Answer item in Model.Answers) { %>
        <% Html.RenderPartial("ShowAnswer", item); %>
<% } %>

For each answer (in the partial view) I have some action buttons (like ratings). I'm using separate form POST's with hidden fields for every button.

The problem is that I can't post the whole QuestionViewData model to my action method cause I only have the Answer object as model in the partial view. However, I need to return the complete question view from that action that takes QuestionViewData as model.

How do I handle such situations?

+1  A: 

Assuming your answers all contain the id of the question, you can post the answers to your controller method, and then populate the rest of your QuestionViewData model type by looking up the questions from the database again. You then return your QuestionViewData object to the view as usual.

Robert Harvey
+1  A: 

As Robert Harvey said, you can look it up from database, but you could also store it in Session:

   [HttpGet]
   public ActionResult ShowQuestion(int id)
   {
       var questionModel = new QuestionViewData();
       //populate questionModel
       Session["CurrentlyHandledQuestion"] = questionModel;
       return View(questionModel);
   }

   [HttpPost]
   public ActionResult ManageAnswer(params)
   {
       var questionModel = (QuestionViewData)Session["CurrentlyHandledQuestion"];
   }

Session data can be lost in many situations, so you should think about situation when questionModel is not available anymore in POST action, but it will work ok most of the time.

LukLed