title: How persist all values in a select made from @Html.ListBoxFor in a MVC.net web page?
body: <p>The Problem: I generate an <code>@Html.ListBoxFor</code> based on a database query in my HttpGet. During my HttpPost, I want to validate that at least one element has been selected. If not, I just want to add a validation message. </p>
  
  <p>The current result: I get the message "Please select at least one item" but now the Select is blank (The select element is there but contains 0 options). I understand that <code>Model.Items</code> will be null in my HttpPost. </p>
  
  <p>Question: <strong>How can I use my model to persist <code>Model.Items</code> to make it not null?</strong></p>
  
  <p>Additional Information: I am trying to avoid using the <code>FormCollection collection</code>  and additional JavaScript. </p>
  
  <p>--The code--</p>
  
  <p>Controller:</p>
  
  <pre><code>public class HomeController : Controller
  {
      public ActionResult Index()
      {
          MyViewModel model = new MyViewModel
          {
              Items = Enumerable.Range(1, 5).Select(x =&gt; new SelectListItem
              {
                  Value = x.ToString(),
                  Text = "item " + x
              })
          };
          return View(model);
      }
  
      [HttpPost]
      public ActionResult Index(MyViewModel model)
      {
  
          return View(model);
      }
  }
  </code></pre>
  
  <p>Model:</p>
  
  <pre><code>public class MyViewModel
  {
      public MyViewModel()
      {
          Items = new List&lt;SelectListItem&gt;();
      }
  
  
      [Required(ErrorMessage = "Please select at least one item")]
      public string[] SelectedItems { get; set; }
  
      public IEnumerable&lt;SelectListItem&gt; Items { get; set; }
  }
  </code></pre>
  
  <p>View:</p>
  
  <pre><code>@model ProjectGenerator.Models.MyViewModel
  
  @using (Html.BeginForm())
  {
      @Html.ListBoxFor(x =&gt; x.SelectedItems, Model.Items)
      @Html.ValidationMessageFor(x =&gt; x.SelectedItems)
      &lt;button type="submit"&gt;OK&lt;/button&gt;
  }
  </code></pre>