Constructing a Select List with OptGroup groups
<p>Current project:</p>

<ul>
<li>ASP.NET 4.5.2</li>
<li>MVC 5</li>
</ul>

<p>I am trying to build a select menu with <code>OptGroups</code> from the Model, but my problem is that I cannot seem to build the <code>OptGroups</code> themselves.</p>

<p>My model:</p>

<pre><code>[DisplayName("City")]
public string CityId { get; set; }
private IList&lt;SelectListItem&gt; _CityName;
public IList&lt;SelectListItem&gt; CityName {
  get {
    List&lt;SelectListItem&gt; list = new List&lt;SelectListItem&gt;();
    Dictionary&lt;Guid, SelectListGroup&gt; groups = new Dictionary&lt;Guid, SelectListGroup&gt;();
    List&lt;Region&gt; region = db.Region.Where(x =&gt; x.Active == true).OrderBy(x =&gt; x.RegionName).ToList();
    foreach(Region item in region) {
      groups.Add(item.RegionId, new SelectListGroup() { Name = item.RegionName });
    }
    List&lt;City&gt; city = db.City.Where(x =&gt; x.Active == true).ToList();
    foreach(City item in city) {
      list.Add(new SelectListItem() { Text = item.CityName, Value = item.CityId.ToString(), Group = groups[item.RegionId] });
    }
    return list;
  }
  set { _CityName = value; }
}
</code></pre>

<p>Each city can be in a region. I want a select menu to group the cities by region. By all that I can figure out, the code above is supposed to do the job, but instead I get a drop-down menu with <strong><em>all cities</em></strong> grouped under the OptGroup named <code>System.Web.Mvc.SelectListGroup</code></p>

<p>The key thing in the above code is that I first iterate through the Regions, and put them into a Dictionary, with the <code>RegionId</code> set to be the key that brings back the <code>RegionName</code> (which itself is formatted as a SelectListGroup).</p>

<p>Then I iterate through the Cities, and assign to each city the group that matches the city’s <code>RegionId</code>.</p>

<p>I have not seen any examples on the Internet that actually pull content from a database -- 100% of all examples use hard-coded <code>SelectListGroup</code> and <code>SelectListItem</code> values.</p>

<p>My View is also correct, AFAIK:</p>

<pre><code>@Html.DropDownListFor(x =&gt; x.CityId, new SelectList(Model.CityName, "Value", "Text", "Group", 1), "« ‹ Select › »", htmlAttributes: new { @class = "form-control" })
</code></pre>

<p>As you can see, the Group is supposed to be brought into the <code>SelectList</code>, and the <code>DropDownList</code> <em>is</em> being created with <code>OptGroups</code>, just not the correct ones.</p>

<p>My resulting drop-down menu looks something like this:</p>

<pre><code>« ‹ Select › »
System.Web.Mvc.SelectListGroup
  City1
  City2
  ...
  LastCity
</code></pre>

<p>When it should be like this:</p>

<pre><code>« ‹ Select › »
Region1
  City2
  City4
  City5
Region2
  City3
  City1
  City6
</code></pre>

<p>Suggestions?</p>

<hr>

<p><strong>Modified solution:</strong> I have followed <a href="https://stackoverflow.com/a/37152663/932002">the solution</a> provided by <a href="https://stackoverflow.com/users/3559349/stephen-muecke">Stephen Muecke</a>, but have modified it slightly.</p>

<p>One of the <em>general</em> rules of MVC is that you have a model that is heavier than the controller, and that the model defines your business logic. Stephen asserts that all database access should be done in the controller. I have come to agree with both.</p>

<p>One of my biggest “issues” is that any creation of a drop-down menu or any other pre-populated form element needs to be called every time the page is called. That means, for either a creation or edit page, you need to call it not only on the [HttpGet] method, but also in the [HttpPost] method where the model is sent back to the view because it did not properly validate. This means you have to add code (traditionally via ViewBags) to <em>each Method</em>, just to pre-populate elements like drop-down lists. This is called code duplication, and is not a Good Thing. There has to be a better way, and thanks to Stephen’s guidance, I have found one.</p>

<p>The problem with keeping data access out of the Model is that you need to populate your model with the data. The problem with avoiding code reuse and avoiding potential errors is that you should not do the job of binding data to elements in the controller. This latter action is <em>business logic</em>, and rightfully belongs in the model. The business logic in my case is that I need to limit user input to a list of cities, grouped by region, that the administrator can select from a drop-down. So while we might <em>assemble</em> the data in the controller, we <em>bind</em> it to the model <em>in</em> the model. My mistake before was doing both in the model, which was entirely inappropriate.</p>

<p>By binding the data to the model in the model, we avoid having to bind it twice - once in each of the [HttpGet] and [HttpPost] methods of the controller. We only have to bind it once, in the model that is handled by both methods. And if we have a more generic model that can be shared between Create and Edit functions, we can do this binding in only one spot instead of four (but I don’t have this degree of genericness, so I won’t give that as an example)</p>

<p>So to start out, we actually peel off the entire data-assembly, and stick it inside its own class:</p>

<pre><code>public class SelectLists {
  public static IEnumerable&lt;SelectListItem&gt; CityNameList() {
    ApplicationDbContext db = new ApplicationDbContext();
    List&lt;City&gt; items = db.City.Where(x =&gt; x.Active == true).OrderBy(x =&gt; x.Region.RegionName).ThenBy(x =&gt; x.CityName).ToList();
    return new SelectList(items, "CityId", "CityName", "Region.RegionName", 1);
  }
}
</code></pre>

<p>This exists within the namespace, but beneath the controller of the section we are dealing with. For clarity’s sake, I stuck it at the very end of the file, just before the closing of the namespace.</p>

<p>Then we look at the model for this page:</p>

<pre><code>public string CityId { get; set; }
private IEnumerable&lt;SelectListItem&gt; _CityName;
public IEnumerable&lt;SelectListItem&gt; CityName {
  get { return SelectLists.CityNameList(); }
  set { _CityName = value; }
}
</code></pre>

<p>Note: Even though the <code>CityId</code> is a <code>Guid</code> and the DB field is a <code>uniqueidentifier</code>, I am bringing this value in as a string through the view because client-side validation sucks donkey balls for Guids. It’s far easier to do client-side validation on a drop-down menu if the <code>Value</code> is handled as a string instead of a Guid. You just convert it back into a Guid before you plunk it back into the master model for that table. Plus, CityName is not an actual field in the City table - it exists purely as a placeholder for the drop-down menu itself, which is why it exists in the <code>CreateClientViewModel</code> for the Create page. That way, in the view we can create a <code>DropDownListFor</code> that explicitly binds the CityId to the drop-down menu, actually allowing client-side validation in the first place (Guids are just an added headache).</p>

<p>The key thing is the <code>get {}</code>. As you can see, no more copious code which does DB access, just a simple <code>SelectLists</code> which targets the class, and a calling of the method <code>CityNameList()</code>. You can even pass variables on to the method, so you can have the same method bring back different variations of the same drop-down menu. Say, if you wanted one drop-down on one page (Create) to have its options grouped by OptGroups, and another drop-down (Edit) to not have any groupings of options.</p>

<p>The actual model ends up being even simpler than before:</p>

<pre><code>@Html.DropDownListFor(x =&gt; x.CityId, Model.CityName, "« ‹ Select › »", htmlAttributes: new { @class = "form-control" })
</code></pre>

<p>No need to modify the element that brings in the drop-down list’s data -- you just call it via <code>Model.ElementName</code>.</p>

<p>I hope this helps.</p>