Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Generally, the <code>Selected</code> property in <code>SelectList</code> will be totally ignored by the HTML helpers unless there's no other option. If <code>DropDownListFor</code> can find the value by other means, it will <em>insist</em> on using that value. </p> <p>In this case, it will use the value of <code>model.PersonType</code>(<code>.ToString()</code>) - but that's not what you want, judging by the <code>model.PersonType.ID</code> you pass to the <code>SelectList</code>.</p> <p>More info in <a href="https://stackoverflow.com/questions/17691742">the answer here</a>.</p> <p><strong>Workaround</strong></p> <p>One easy workaround that should work would be to set:</p> <pre><code>ViewData["PersonType"] = model.PersonType.Id. </code></pre> <p>The helper looks in ModelState first if it exists - i.e. on POST. This should work already, since <code>ModelState["PersonType"]</code> will be populated with the actual selected value that was posted.</p> <p>After ModelState it will look in <code>ViewData</code> - with <code>ViewData["PersonType"]</code> first, and only then <code>ViewData.Model.PersonType</code>. In other words, you can "override" the value on your model with a value set directly on <code>ViewData</code>.</p> <p><strong>Better (IMO) solution</strong></p> <p>The more general, "better practice", way to solve it (which also avoids having a custom model binder in order to translate the POST'ed ID back to <code>PersonType</code>) is to use a ViewModel instead of working with full models in your view:</p> <ul> <li>Have a <code>PersonTypeID</code> property - instead of <code>PersonType</code>.</li> <li>Populate it with <code>PersonType.ID</code></li> <li>use this in your view <ul> <li>VB.NET: <code>Html.DropDownListFor(Function(model) model.PersonTypeID)</code>, or</li> <li>C#: <code>Html.DropDownListFor(model =&gt; model.PersonTypeID)</code></li> </ul></li> <li>When form is POST'ed, translate the ViewModel (including <code>PersonTypeID</code> => <code>PersonType</code>) back into the actual model in your POST Action.</li> </ul> <p>This may seem like more work, but generally there tend to be many occasions in a project where you need more view-specific representations of your data to avoid too much inline Razor code - so translating from business objects to view models, while it may seem redundant and anti-DRY at times, tends to spare you of a lot of headaches.</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.
    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