Search code examples
c#asp.net-mvchtml.dropdownlistfor

Html.DropDownList not setting selected item on GET


I have this problem were I am setting a selectlist with a selected item. On GET request the select list is populated but the selected item is not set. On POST request the select list is populated with the new selected value.

Code is the same for both ActionResult functions as is the view (both using the same view).

This is part of my Student class

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

This is the code in my controller:

public ActionResult Index()
{
    Student student = _dB.Students.Where(std => std.AccountID == accountID).FirstOrDefault();

    student.Titles = new SelectList(_dB.Titles, "Id", "Description", student.Title);

    return View(student);
}


    [HttpPost]
    public ActionResult Index(Student student)
    {

        if (ModelState.IsValid)
            {
                Student studentSave = _dB.Students.Where(stud => stud.StudentID == student.StudentID).FirstOrDefault();
                studentSave.Name = student.Name;
                studentSave.Surname = student.Surname;
                studentSave.Email = student.Email;
                studentSave.Title = student.Title;
                studentSave.DOB = student.DOB;
                studentSave.Telnum = student.Telnum;
                studentSave.AddressLine1 = student.AddressLine1;
                studentSave.AddressLine2 = student.AddressLine2;
                studentSave.Town = student.Town;
                studentSave.PostCode = student.PostCode;
                studentSave.Country = student.Country;

                _dB.SaveChanges();
                
            }

            ViewBag.Submitted = true;

            student.Titles = new SelectList(_dB.Titles, "Id", "Description", student.Title);

            return View(student);

    }

This is the code in my View

@Html.DropDownList("Title", Model.Titles, new { @class = "form-control shadow-none" })
                                    @Html.ValidationMessageFor(model => model.Title, "", new { @class = "text-danger" })

Values are passed correctly when debugging up to Html.DropDownList but on render the selected item is not set (when performing GET request).

I have tried various methods of populating the select list and all have rendered the same result.

Has anyone experienced something similar?


Solution

  • You need to provide the Title value to the fourth parameter for DropDownList(String, String, IEnumerable<SelectListItem>, Object, Object).

    @Html.DropDownList("Title", 
        "",
        Model.Titles, 
        Model.Title,
        new { @class = "form-control shadow-none" })
    

    Alternatively, you can use Html.DropDownListFor to bind the Title value to the drop-down list.

    @Html.DropDownListFor(model => model.Title, 
        Model.Titles, 
        new { @class = "form-control shadow-none" })