Search code examples
asp.net-mvcdropdownbox

MVC Dropdownlist how to keep saved value when editing


I have a dropdownlist populated from database. When I go to the edit page to change any field the dropdownlist sets it self to the first value populated in the list. My question is how can I keep the selected value when I try to edit some other fields?

This is view:

@Html.DropDownListFor(m => m.DEPTID, (IEnumerable<SelectListItem>)ViewBag.DEPTID, htmlAttributes: new { @class = "form-control" })

This is controller:

public ActionResult Edit(string id, string id2, int id3)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }

        JOB jOB = db.JOBs.Find(id, id2, id3);
        if (jOB == null)
        {
            return HttpNotFound();
        }
        ViewBag.DEPTID = new SelectList(db.DEPARTMENTs.ToList(), "DEPTID", "DEPTID");
        return View(jOB);
    }

This is model:

 public class JOB
    {
            public string DEPTID { get; set; }

Solution

  • You cannot give the ViewBag property the same name as the model property your binding to.

    In the GET method change the name to (say)

    ViewBag.DepartmentList = new SelectList(db.DEPARTMENTs, "DEPTID", "DEPTID");
    

    and in the view

    @Html.DropDownListFor(m => m.DEPTID, (SelectList)ViewBag.DepartmentList, new { @class = "form-control" })
    

    If the value of DEPTIDmatches one of the option values, then that option will be selected when the view is rendered.