'Cannot pass new selected dropdown value to the controller

I have an MVC application. Here is a part of my code:

View Model:

public class StudentViewModel
{
    public int Id { get; set; }
    public int? DepartmentId { get; set; }
    public string Name { get; set; }
    public string Department { get; set; }

    public IEnumerable<SelectListItem> AllDepartments { get; set; }
}

View:

@Html.DropDownListFor(model => model.DepartmentId, Model.AllDepartments)

Controller:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit(StudentViewModel studentViewModel)
    {

After the user changes the department selection in the dropdown and submits, for some reason the studentViewModel.DepartmentId contains the old DepartmentId. studentViewModel.Name does contain the new value. What am I missing?



Solution 1:[1]

From the comments, you have included another control for property DepartmentId before the dropdownlist. The DefaultModelBinder reads all form values in order (plus route values, query string values etc). Once a property value has been set, any subsequent values for the same property are ignored.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1