Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You could use AJAX. subscribe to the change event of the dropdownlist and trigger an AJAX request to a controller action passing along the selected category. The action will query the database for corresponding subcategories and return a partial view with corresponding checkboxes which will be injected into the DOM.</p> <p>So let's suppose that you already have a dropdownlist for the categories in your view:</p> <pre><code>@Html.DropDownListFor( x =&gt; x.CategoryId, Model.Categories, new { id = "categories", data_subcategoriesurl = Url.Action("subcategories", "somecontroller") } ) </code></pre> <p>and some div which will contain the subcategories somewhere on the page:</p> <pre><code>&lt;div id="subcategories"&gt; @Html.EditorFor(x =&gt; x.SubCategories, "SubCategories") &lt;/div&gt; </code></pre> <p>and you could then have a <code>SubCategories.cshtml</code> partial which will render the list of checkboxes:</p> <pre><code>@model IList&lt;CategoryViewModel&gt; @{ // we change the HTML field prefix so that input elements // such as checkboxes have correct names in order to be able // to POST the values back ViewData.TemplateInfo.HtmlFieldPrefix = "SubCategories"; } @for (var i = 0; i &lt; Model.Count; i++) { &lt;div&gt; @Html.LabelFor(x =&gt; x[i].IsSelected, Model.CategoryName) @Html.CheckBoxFor(x =&gt; x[i].IsSelected) &lt;/div&gt; } </code></pre> <p>Now you could subscribe to the change event of the dropdown in a separate javascript file:</p> <pre><code>$(function() { $('#categories').change(function() { var subcategoriesUrl = $(this).data('subcategoriesurl'); var selectedCategoryId = $(this).val(); $('#subcategories').load(subcategoriesUrl, { id: selectedCategoryId }); }); }); </code></pre> <p>and finally the <code>SubCategories</code> action which will be invoked with AJAX:</p> <pre><code>public ActionResult SubCategories(int? id) { var subCategories = Repository.GetSubCategories(id); return View(subCategories); } </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.
 

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