Note that there are some explanatory texts on larger screens.

plurals
  1. PO DropDownListFor() not populating with preselected item from ViewModel?
    primarykey
    data
    text
    <p>In my project the DropDownListFor(x => x code sits in an EditorTemplate. It is used to populate a table of data one of the fields of the table is the drop down list. Whilst everything is rendering with no issues, the drop down list does not default to the pre-selected item I am settings in the ViewModel. What am I not seeing?</p> <p>Code as follows:</p> <p>ViewModel:</p> <pre><code>public class FooDetailViewModel : ViewModelBase { public List&lt;FooPermissionObject&gt; FooPermissions { get; set; } } </code></pre> <p>The Strongly-typed model object:</p> <pre><code>public class FooPermissionObject { public string Name { get; set; } public int Reason { get; set; } public IEnumerable&lt;SelectListItem&gt; Reasons { get; set; } public bool Selected { get; set; } } </code></pre> <p>The controller:</p> <pre><code>var viewModel = new StockLineManagementDetailViewModel(); using (_model) { foreach (var company in _model.GetAllRecords&lt;Company&gt;()) { var permissionModel = new FooPermissionObject { Name = company.Name, Selected = true, Reasons = _model.GetAllRecords&lt;FooPermissionReason&gt;() .ToList() .Select(x =&gt; new SelectListItem { Value = x.FooPermissionReasonId.ToString(), Text = x.FooPermissionReasonDesc }), Reason = record.FooPermissionReasonId }; viewModel.FooPermissions.Add(permissionModel); } } </code></pre> <p>The View: </p> <pre><code>&lt;table id="myTable" class="tablesorter" style="width:98%"&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt; Name &lt;/th&gt; &lt;th&gt; Excluded &lt;/th&gt; &lt;th&gt; Reason for Exclusion &lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; @Html.EditorFor(x =&gt; x.FooPermissions) &lt;/tbody&gt; &lt;/table&gt; </code></pre> <p>The EditorTemplate:</p> <pre><code>@model FooPermissionObject &lt;tr&gt; &lt;td&gt; @Html.DisplayFor(x =&gt; x.Name, new { @readonly = "readonly"}) @Html.HiddenFor(x =&gt; x.Name) &lt;/td&gt; &lt;td&gt; @Html.CheckBoxFor(x =&gt; x.Selected) &lt;/td&gt; &lt;td&gt; @Html.DropDownListFor(x =&gt; x.Reason, Model.Reasons) &lt;/td&gt; &lt;/tr&gt; </code></pre> <p>Anyone got any ideas why this wouldn't populate the DropDownListFor with the Object represented by the Reason value from the Reasons collection?</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