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?
Code as follows:
ViewModel:
public class FooDetailViewModel : ViewModelBase
{
public List<FooPermissionObject> FooPermissions { get; set; }
}
The Strongly-typed model object:
public class FooPermissionObject
{
public string Name { get; set; }
public int Reason { get; set; }
public IEnumerable<SelectListItem> Reasons { get; set; }
public bool Selected { get; set; }
}
The controller:
var viewModel = new StockLineManagementDetailViewModel();
using (_model)
{
foreach (var company in _model.GetAllRecords<Company>())
{
var permissionModel = new FooPermissionObject
{
Name = company.Name,
Selected = true,
Reasons = _model.GetAllRecords<FooPermissionReason>()
.ToList()
.Select(x => new SelectListItem
{
Value = x.FooPermissionReasonId.ToString(),
Text = x.FooPermissionReasonDesc
}),
Reason = record.FooPermissionReasonId
};
viewModel.FooPermissions.Add(permissionModel);
}
}
The View:
<table id="myTable" class="tablesorter" style="width:98%">
<thead>
<tr>
<th>
Name
</th>
<th>
Excluded
</th>
<th>
Reason for Exclusion
</th>
</tr>
</thead>
<tbody>
@Html.EditorFor(x => x.FooPermissions)
</tbody>
</table>
The EditorTemplate:
@model FooPermissionObject
<tr>
<td>
@Html.DisplayFor(x => x.Name, new { @readonly = "readonly"})
@Html.HiddenFor(x => x.Name)
</td>
<td>
@Html.CheckBoxFor(x => x.Selected)
</td>
<td>
@Html.DropDownListFor(x => x.Reason, Model.Reasons)
</td>
</tr>
Anyone got any ideas why this wouldn't populate the DropDownListFor with the Object represented by the Reason value from the Reasons collection?