Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The <code>Selected</code> property in <code>SelectListItem</code> is mostly useless <a href="https://stackoverflow.com/questions/17691742/dropdownlistfor-not-respecting-selected-property-of-selectlist">(more about that in my answer here)</a>. The HTML helpers will ignore it in most cases. Instead, in your case, they will look at the values of:</p> <ul> <li><code>ModelState["IncludesWeekends"]</code></li> <li><code>ViewData["IncludesWeekends"]</code></li> <li><code>Model.IncludesWeekends</code></li> </ul> <p>... and turn whatever value they find into a <code>String</code>, then use that as the selected value. </p> <p>You have an <code>IncludesWeekends</code> property on your model, so it will do:</p> <pre><code>Model.IncludesWeekends.ToString() </code></pre> <p>... which - judging from your code - will result in True" or "False" (since it's a <code>bool</code>).</p> <p>In your case, you're using <code>c.Id.ToString()</code> as the <code>&lt;option&gt;</code> values for your dropdown, and since the helper won't find its chosen string ("True"/"False") among those values ("1"/"0"), it won't select anything.</p> <p>Ways around it:</p> <ol> <li><p>(Easiest way): Accept using "True" and "False" as your <code>&lt;option&gt;</code> values rather than integer IDs.</p></li> <li><p>(The almost-as-easy-but-not-very-clean way): Set <code>ViewData["IncludesWeekends"]</code> to the value you want selected (i.e., the <code>Id</code>). This works, because the helper will look at that before <code>Model.IncludesWeekends</code>.</p></li> <li><p>Use a view model, where you have an <code>IncludesWeekendsId</code> property, then use that to generate the dropdown, rather than <code>IncludesWeekends</code>:</p> <p><code>&lt;%= Html.DropDownList("IncludesWeekendsId", Model.YesNoList) %&gt;</code></p> <p>or</p> <p><code>&lt;%= Html.DropDownListFor(m =&gt; m.IncludesWeekendsId, Model.YesNoList) %&gt;</code></p> <p>Then, when returning from the view, translate <code>IncludesWeekendsId</code> back into the proper value on your model.</p></li> </ol> <p>In this case, I'd probably go with <strong>1</strong> if I wasn't in a pedantic mood. But solution <strong>3</strong> is a general, and mostly clean, way to solve this in cases where you have to use different values for your dropdown items than the value of your model's property converted to a string.</p>
 

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