title: MVC: Selected values in a listbox when the user is on the edit page
body: <p>Im using MVC3 EF-model first on my project.</p>
  
  <p>When a user create a question, he/she can choose multiple CoreValues from a ListBox.
  When the user goes to the edit page to change the CoreValues on the question I want that the listbox has those corevalues already selected any idea on how I could do that?</p>
  
  <p>This is my ViewModel:</p>
  
  <pre><code>public class AdminEditViewModel
  {
      public string QuestionText { get; set; }
      public string SubjecTypeName { get; set; }
      public string CoreValueName { get; set; }
      public SelectList SubjectTypes { get; set; }
      public IEnumerable&lt;string&gt; SelectedValuesOfCoreValues { get; set; }
      public IEnumerable&lt;CoreValue&gt; CoreValues { get; set; }
  }
  </code></pre>
  
  <p>and this is my GET and POST actions in my controller:</p>
  
  <pre><code>public ActionResult Edit(int id)
  {
              Question question = AdminRep.GetQuestionById(id);
              AdminEditViewModel model = new AdminEditViewModel();
              List&lt;SubjectType&gt; subjectypes = AdminRep.GetAllSubjectTypesById();
              model.CoreValues = AdminRep.GetAllCorevaluesById();
              model.QuestionText = question.QuestionText;
              model.SubjectTypes = new SelectList(subjectypes, "Id", "Name",question.SubjectType.First().Id);
  
  
              return View(model);
  }
  
          //
          // POST: /Admin/Edit/5
  
  [HttpPost, ActionName("Edit")]
  public ActionResult EditConfirmed(int id, AdminEditViewModel model)
  {
  
              if (ModelState.IsValid)
              {
                  Question question = AdminRep.GetQuestionById(id);
                  question.QuestionText = model.QuestionText;
                  question.SubjectType.Clear();
                  question.CoreValue.Clear();
                  foreach (var item in model.SelectedValuesOfCoreValues)
                  {
                      var CoreValueID = int.Parse(item);
                      var GetAllCoreValuesID = AdminRep.GetByCoreValueID(CoreValueID);
                      question.CoreValue.Add(GetAllCoreValuesID);
  
                  }
                  var SubjectTypeID = int.Parse(model.SubjecTypeName);
                  var getallS = AdminRep.GetBySubjectTypeID(SubjectTypeID);
                  question.SubjectType.Add(getallS);
                  AdminRep.save();
                  return RedirectToAction("Index");
              }    
               return View(model);
  }
  </code></pre>
  
  <p>and my View:</p>
  
  <pre><code>&lt;div class="editor-field"&gt;
      @Html.ListBoxFor(m =&gt; m.SelectedValuesOfCoreValues, new MultiSelectList(Model.CoreValues, "Id", "Name"), new { @class = "selectstyle" })
      @Html.ValidationMessageFor(model =&gt; model.CoreValueName)
  &lt;/div&gt;
  </code></pre>
  
  <p>Thanks in advance!</p>