In my web application, there is a combo box to select employees from the list.
When I choose it from the combo box and submit the form, the selected value ID is going to the database and is saved.
But when I retrieve the same data for the view, in the controller I can see the same data in the database retrieving and passing to the partial view.
But there the combo box value is the first value always. Not show the saved value in the combo box.
This is the code, I'm loading the employee list to the session and here I'm loading the data to the combo box from the session. As you can see in the picture item.Req_For
contains the value of 35
but the view shows the first value of the combo box list.
<div class="row">
<div class="col-md-6 col-sm-6">
<div class="form-group">
<label>Vehicle Owner</label>
<div class="col-md-8">
@Html.DropDownListFor(model => item.Req_For, Employees ,new { @class = "js-dropdown", @disabled = "disabled" })
@Html.ValidationMessageFor(model => item.Req_For, "", new { @class = "text-danger" })
</div>
</div>
</div>
</div>
To define a default selection in the DropDownList
it's necessary to set Selected
property to true
:
@Html.DropDownListFor(m => Employees.GetEnumerator().Current,
Employees.Select(d =>
{
return new SelectListItem() { Text = d.EmployeName, Value = d.EmployeId, Selected= (d.EmployeId == item.Req_For) };
}),
null, new { @class = "js-dropdown", @disabled = "disabled" })