Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>At no point in your population of the List in GetServerTypes() do you specify that any of the items are selected. This is something you need to do manually, as MVC3 isn't smart enough to infer it for you in the DropDownListFor method. This is further complicated by the fact that you are not using a single model.</p> <p>A better way to do this might be:</p> <p>(Keep in mind in the below code, I'm assuming that the Server class has a primary id called "Id")</p> <p>For the controller code:</p> <pre><code>public ActionResult List() { IEnumerable&lt;Server&gt; s = GetServers(); ViewData["ServerTypes"] = GetServerTypes(s); return View("List", s); } private Dictionary&lt;int, SelectList&gt; GetServerTypes(IEnumerable&lt;Server&gt; s) { Dictionary&lt;int, SelectList&gt; sl = new Dictionary&lt;int, SelectList&gt;(); IEnumerable&lt;ServerType&gt; items = (from t in _entities.ServerTypes select t); foreach (Server srv in s) { sl.Add(srv.Id, new SelectList(items, "Id", "Description", srv.ServerTypeId)); } return sl; } </code></pre> <p>For the view code:</p> <p>(Also note below how the I've corrected the arguments used in the lambda functions)</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; modelItem.ServerTypeId, (IEnumerable&lt;SelectListItem&gt;)(ViewData["ServerTypes"][item.Id])) &lt;/td&gt; &lt;td&gt; @Html.DisplayFor(modelItem =&gt; modelItem.Name) &lt;/td&gt; &lt;/tr&gt; } &lt;/table&gt; </code></pre>
 

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