Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>OK, this one really confused me but I think I've got it figured out.</p> <p>The problem <em>I</em> had getting the <code>MultiSelectList</code> to display with defaults selected was that I was using <code>@Html.DropDownListFor(...)</code> to display the multi select list instead of <code>@Html.ListBoxFor(...)</code>. Confusingly, <code>DropDownListFor</code> <em>will display</em> a multi select list if you specify the HTML attributes to force it to do so, but the default values <em>will not</em> work, because it's only intended to have one default - the following will therefore <em>not</em> have any defaults selected:</p> <pre><code>List&lt;string&gt; myStrings; myStrings = new List&lt;string&gt;(); myStrings.Add("aaa"); myStrings.Add("bbb"); myStrings.Add("ccc"); ViewData["MyStringsDropdown"] = new MultiSelectList( myStrings.Select(abc =&gt; new { StringId = abc, Title = abc + "Title" }), "StringId", "Title", myStrings.Where(str =&gt; str == "aaa" || str == "ccc").ToList() ); ... @Html.DropDownListFor(model =&gt; model.MyStrings, (MultiSelectList)ViewData["MyStringsDropdown"], new { size = "10", multiple = "multiple" }) </code></pre> <p>However, the following <em>will</em> display the defaults of "aaa" and "ccc" as selected:</p> <pre><code>@Html.ListBoxFor(model =&gt; model.MyStrings, (MultiSelectList)ViewData["MyStringsDropdown"], new { size = "10", multiple = "multiple" }) </code></pre> <p>But here's the real kicker; ASP.NET sometimes seems <em>cache</em> the type of the control, so you can replace the <code>DropDownListFor</code> with the <code>ListBoxFor</code> and it will still not pre-select any defaults <em>until you restart the IIS worker process</em>. I find that really strange, and it threw me for a while.</p>
    singulars
    1. This table or related slice is empty.
    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. This table or related slice is empty.
    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