Home > OS >  Default value to combo box not assigning in partial view
Default value to combo box not assigning in partial view

Time:01-18

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_Forcontains the value of 35 but the view shows the first value of the combo box list.

<div >
   <div >
      <div >
         <label>Vehicle Owner</label>
         <div >
            @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>

Screen Shot

CodePudding user response:

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" })
  •  Tags:  
  • Related