Note that there are some explanatory texts on larger screens.

plurals
  1. POCorrect way to use DropDownListFor with a list of primitive types?
    primarykey
    data
    text
    <p>Here is the relevant code. Mind you, I did this in Notepad++ instead of copying in my code for my project at work. If I misspelled a class name in it, assume it is not misspelled in my code. No compile errors.</p> <p>Model:</p> <pre><code>public class MyViewModel { public int SelectedSomething { get; set; } public IList&lt;int&gt; Somethings { get; set; } } </code></pre> <p>Controller:</p> <pre><code>public class MyController { public ActionResult Index() { var viewModel = new MyViewModel(); viewModel.Somethings = Enumerable.Range(1, 12).ToList(); return View(viewModel); } } </code></pre> <p>View (Razor):</p> <pre><code>@Html.DropDownListFor(x =&gt; x.SelectedSomething, new SelectList(Model.Somethings, Model.SelectedSomething), "Select an Option") </code></pre> <p>This will "work", but won't set values on any of the rendered <code>option</code> elements in the <code>select</code>:</p> <pre><code>&lt;select&gt; &lt;option value=""&gt;Select an Option&lt;/option&gt; &lt;option&gt;1&lt;/option&gt; &lt;option&gt;2&lt;/option&gt; &lt;option&gt;3&lt;/option&gt; &lt;option&gt;4&lt;/option&gt; &lt;option&gt;5&lt;/option&gt; &lt;option&gt;6&lt;/option&gt; &lt;option&gt;7&lt;/option&gt; &lt;option&gt;8&lt;/option&gt; &lt;option&gt;9&lt;/option&gt; &lt;option&gt;10&lt;/option&gt; &lt;option&gt;11&lt;/option&gt; &lt;option&gt;12&lt;/option&gt; &lt;/select&gt; </code></pre> <p>I know of the <a href="http://msdn.microsoft.com/en-us/library/dd505286%28v=vs.100%29.aspx" rel="noreferrer"><code>SelectList</code> constructor</a> that takes in the property names to use to render the <code>value</code> and <code>text</code> in the <code>option</code> elements, but it is of no use (<em>that I can see</em>) when using a collection of a primitive type like an <code>int</code>.</p> <p>Question:</p> <p>I know I can change my view model's <code>IList&lt;int&gt;</code> to <code>IList&lt;SelectListItem&gt;</code>, and create <code>SelectListItem</code> objects to represent each <code>int</code>, but that seems a bit ridiculous (as I think the constructor shouldn't leave the values blank, and should default to using the text). Am I missing something obvious here, or am I going to have to move away from using primitive types here?</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.
 

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