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?
I can’t see any code where you are setting selected = true in your select list. You are setting the Selected property of your FooPermissionObject but that is irrelevant your drop down list is bound to the reasons collection. You want something like this:
Replacing some condition or other with whatever your criteria is to say which item should be selected.
EDIT:
A better way might be as below:
The params to the constructor of SelectList are: Collection to bind, value field, text field, selected value.