Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>This tends to stump people a lot - apparently the roadmap for MVC 5 includes more intuitive DropDownList helpers.</p> <p>When you do:</p> <pre><code>@Html.DropDownListFor(x =&gt; x.TimeOption ...) </code></pre> <p>... the HTML helper will do everything in its power <em>not</em> to use the value you set to <code>Selected = true</code> in your <code>SelectList</code>. It will:</p> <ul> <li>Try to get it from <code>ModelState</code> - which it won't get on the GET request</li> <li>Try to get it from <code>ViewData</code> - which it <em>will</em> get, because you have a <code>TimeOption</code> property on your model.</li> </ul> <p>Only if both of those attempts fail, will it succumb, and use what you asked it to use.</p> <p>So, in your case, it will use the current value of <code>TimeOption</code> on your model as the selected value. Which should be fine, because that's what you asked for in your <code>SelectList</code> anyway (<code>(int)Model.TimeOption</code>), right?</p> <p>Wrong. Because it will <em>not</em> cast your property (<code>enum</code>?) to <code>int</code> like you do. It will convert it to a string. For an <code>enum</code> that yields the enumeration's name - e.g. <code>PastMonth</code>. If <code>TimeOption</code> is a custom class of yours, it will be the result of <code>ToString()</code>.</p> <p>Then, when it doesn't find that string as one of your <code>&lt;select&gt;</code> values (because they're all integers), it decides not to make anything selected.</p> <p>In short: <code>SelectListItem.Selected</code> has no effect on the helper. If your helper call specifies a name (either literally or through a lambda expression), the helper will use anything in <code>ModelState</code> or <code>ViewData</code> with that name, and convert it to a string.</p> <p>In most cases this happens with enumerations. The easiest way to get around it is to use the enumeration's name, rather than its int representation, as the value for the <code>SelectListItem</code>.</p>
    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.
 

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