Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>We use Serge Zab's helper for optgroup dropdowns. Here is a sample:</p> <p><strong>The viewmodel:</strong></p> <pre><code>public class OurViewModel { public int? TypeId { get; set; } public IEnumerable&lt;GroupedSelectListItem&gt; GroupedTypeOptions { get; set; } } </code></pre> <p><strong>The controller:</strong></p> <pre><code>public ActionResult Add() { var model = new OurViewModel { // fill with initial values }; PutTypeDropDownInto(model); return View(model); } [NonAction] private void PutTypeDropDownInto(OurViewModel model) { model.GroupedTypeOptions = _repos.GetTypes() .OrderBy(t =&gt; t.Category.EnglishName).ThenBy(t =&gt; t.EnglishName) .Select(t =&gt; new GroupedSelectListItem { GroupKey = t.Category.RevisionId.ToString(), GroupName = t.Category.EnglishName, Text = t.EnglishName, Value = t.RevisionId.ToString() } ); } </code></pre> <p><strong>The view</strong></p> <pre><code>@Html.DropDownGroupListFor(m =&gt; m.TypeId, Model.GroupedTypeOptions, "[Select a type]") </code></pre> <p>Note that you can't use a regular SelectList. You have to use a collection of his GroupedSelectListItem class. Also, our solution doesn't use viewbag. The dropdown list is strongly typed on the viewmodel.</p> <p><strong>Update</strong></p> <p>To get the html helper to work in your view, the view needs to be able to find it. You can either add a @using directive at the top of the view with your MyExtensionClass.cs namespace, or add the namespace to the view-specific web.config, like so:</p> <pre><code>&lt;pages pageBaseType="System.Web.Mvc.WebViewPage"&gt; &lt;namespaces&gt; &lt;add namespace="System.Web.Mvc" /&gt; &lt;add namespace="System.Web.Mvc.Ajax" /&gt; &lt;add namespace="System.Web.Mvc.Html" /&gt; &lt;add namespace="System.Web.Routing" /&gt; &lt;add namespace="Microsoft.Web.Mvc" /&gt; &lt;add namespace="Namespace.For.MyExtensionClass" /&gt; &lt;/namespaces&gt; &lt;/pages&gt; </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload