Search code examples
asp.net-mvchtml-selectselectedvalue

Get SelectedValue from List<SelectListItem> DDL


If I have a method like this:

public static List<SelectListItem> lstPassFail()
{
    List<SelectListItem> lstPossiblePassFail = new List<SelectListItem>()
    {
        new SelectListItem() { Text = "Pass", Value = "Pass" },
        new SelectListItem() { Text = "Fail", Value = "Fail" },
    };

    return lstPossiblePassFail;
}

Then in my Edit Action I do this:

ViewBag.PassFail = ClassName.lstPassFail();

Then in my Edit View I do this:

@Html.DropDownList("PassFail", (List<SelectListItem>)ViewBag.PassFail, "-- Please Select a Result --", htmlAttributes: new { @class = "form-control" } )

Since this record already exists in the database and that field already has a value how do I display that selectedvalue, instead of the DDL selecting the very first option by default?

I know that you can do this with an overloaded method for SelectList, but can this be done in the way I portrayed above?

Any help is appreciated.


Solution

  • I have figured this out.

    I changed:

    ViewBag.PassFail = ClassName.lstPassFail();
    

    to

    ViewBag.PassFail = new SelectList(ClassName.lstPassFail(), "Value", "Text", chosenWTest.PassFail);
    

    Then in my view I changed the dropdownlist to this

    @Html.DropDownList("PassFail", null, "-- Please Select a Result --", htmlAttributes: new { @class = "form-control" } )
    

    This saved the value for that field in that record.