Note that there are some explanatory texts on larger screens.

plurals
  1. PORazor and Html.DropDownList: Setting selected values for a dropdown for each row in a list?
    primarykey
    data
    text
    <p>This seems like it should be simple, but I can't figure out how to make it work.</p> <p>My data model has a "Server" table, and a "ServerType" table. PKs for both tables are ints, and Server has a field ServerTypeId which is a fk to ServerType.Id.</p> <p>I have a Razor List.cshtml that is typed to IEnumerable:</p> <pre><code>@model IEnumerable&lt;Server&gt; &lt;table border="1"&gt; &lt;tr&gt; &lt;th&gt; Server Type &lt;/th&gt; &lt;th&gt; Name &lt;/th&gt; &lt;/tr&gt; @foreach (var item in Model) { &lt;tr&gt; &lt;td&gt; @Html.DropDownListFor(modelItem =&gt; item.ServerTypeId, (IEnumerable&lt;SelectListItem&gt;)ViewData["ServerType"]) &lt;/td&gt; &lt;td&gt; @Html.DisplayFor(modelItem =&gt; item.Name) &lt;/td&gt; &lt;/tr&gt; } &lt;/table&gt; </code></pre> <p>My controller has:</p> <pre><code> public ActionResult List() { var s = GetServers(); ViewData["ServerType"] = GetServerTypes(); return View("List", s); } private List&lt;SelectListItem&gt; GetServerTypes() { string id; SelectListItem si; List&lt;SelectListItem&gt; sl = new List&lt;SelectListItem&gt;(); IQueryable&lt;ServerType&gt; items = (from t in _entities.ServerTypes select t); foreach (var item in items) { id = item.Id.ToString(); si = new SelectListItem { Value = id, Text = item.Description }; sl.Add(si); } return sl; } </code></pre> <p>This displays the data, but the value in the dropdown is not selected. I've tried both Html.DropDownList and Html.DropDownListFor, with different permutation of names for the ViewData property, with and without the Id at the end.</p> <p>Do I need to create a viewmodel that has copies of the ServerType in order to set the Selected property? Or is it a problem because my ids are ints, and the SelectItemList Value property is a string? </p>
    singulars
    1. This table or related slice is empty.
    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