title: MVC, passing classes between controller and view
body: <p>I have a scenario as follows; a "Survey" contains a list of type "Question"; "Question" is made up of an id and a string called "Text".  Here are the class definitions:</p>
  
  <pre><code>public class Survey
  {
      public int SurveyId { get; set; }
      public string Title { get; set; }
      public List&lt;Question&gt; Questions { get; set; }
  
      public Survey()
      {
          this.Questions = new List&lt;Question&gt;();
      }
  }
  
  public class Question
  {
      public int QuestionId { get; set; }
      public string QuestionText { get; set; }
      public int OwningSurveyId { get; set; }
  }
  </code></pre>
  
  <p>I would like to be able to link from the page for a specific Survey to create a new Question (which works fine), but when the Question form is submitted I want to do two things; 1) ensure that the OwningSurveyId is set correctly, and 2) add the Question to Survey.Questions List.  </p>
  
  <p>I am open to any solution to get this functionality - the approach I've taken may not be the best.  What I decided to do was pass the Survey object into the Create form for the Question, so that when the form is submitted, the form contains both objects, and so I can perform both tasks above (1 &amp; 2) correctly.</p>
  
  <p>I set up the Create Question page in the QuestionController as follows:</p>
  
  <pre><code>// GET: /Question/Create
  
      public ActionResult Create(Survey OwningSurvey)
      {
          return View(OwningPulse);
      }
  
  [HttpPost]
      public ActionResult Create(Pulse OwningPulse, Question NewQuestion)
      {
          ModelState["OwningSurveyId"].Errors.Clear();
  
          if (ModelState.IsValid)
          {
              OwningPulse.Questions.Add(NewQuestion);
              db.Questions.Add(NewQuestion);
              db.SaveChanges();
              return RedirectToAction("Index", "Survey");
          }
  
          return View(OwningSurvey);
      }
  </code></pre>
  
  <p>and the Create.cshtml file for the Question has the following:</p>
  
  <pre><code>@model MoodTool.Interface.Models.Survey
  
  @{
  ViewBag.Title = "Create";
  
  var Question = new MoodTool.Interface.Models.Question();
  Question.OwningPulseId = Model.SurveyId;
  }
  
  @using (Html.BeginForm("Create", "Question", "{NewQuestion}", FormMethod.Post, new { NewQuestion = Question }))
  {... code follows
  </code></pre>
  
  <p>The problem I have is that the value of the "Model" in the .cshtml file is null, and therefore the page crashes.  The value of OwningSurvey in the Create method of the Question controller ("GET" version) is also null.</p>
  
  <p>Can anyone guide me in the right direction?  I realise that I'm probably doing something either majorly wrong (design patterns), or have made a simple syntax error, but I'm new to MVC and going round in circles.</p>
  
  <p>Thanks</p>