0

I have this to populate a drop down list in an ASP.NET MVC view.

C#

ViewBag.Employees = new SelectList(
            _employeeRepository.GetAll(), 
            "ID", 
            "LastName",
            employeeToClientContract.EmployeeID);

CSHTML

@Html.DropDownListFor(model => model.EmployeeID, ViewBag.Employees as IEnumerable<SelectListItem>, "Please select")

NOTE: For some reason this works

ViewBag.OverridePhysicians = new SelectList(
            _employeeRepository.GetAll().Where(e => e.EmployeeTypes.TypeType == 1), 
            "ID", 
            "LastName",
            employeeToClientContract.OverridePhysicianID);

@Html.DropDownListFor(model => model.OverridePhysicianID, ViewBag.OverridePhysicians as IEnumerable<SelectListItem>, "Please select")

Debugging this I can see that the Selected property is set to true when it should be. But when the view is rendered, none of the options in the list is selected.

Any ideas?

UPDATE: The problem wasn't with any of the control configurations. My problem was extra spaces in my URL. All I had to do was call .Trim() to fix the problem.

$('#itemsTable').bootstrapTable({

        }).on('click-row.bs.table', function (e, row, $element) {
            window.location.href = "/EmployeeToClientContract/Edit?employeeId=" + row[0].toString().trim() + "&clientContractId=" + row[2].toString().trim();
        });
1
  • 1
    model.EmployeeID contain a value? The selected field of SelectList is not used and will be ignored, don't even bother with it. Commented Apr 10, 2015 at 15:31

1 Answer 1

2

DropDownListFor Helper use model.EmployeeID value to set selected value in DropdownList. This property has value?

Also, why are facing so much difficults with SelectList? Don't you want to populate ViewBag like this:

ViewBag.Employees = _employeeRepository
.GetAll()
.Select(x => new SelectListItem
{
     Text = x.LastName,
     Value = x.ID.ToString(),
     Selected = employeeToClientContract.EmployeeID == x.ID
}); 
Sign up to request clarification or add additional context in comments.

2 Comments

Yes. The return object to the view is correctly hydrated.
@kyle This is working solution based on everything you have provided. Please mark this as an answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.