0

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.

Grizzly
  • 5,873
  • 8
  • 56
  • 109
  • Use a model that has a property named `PassFail` instead of `ViewBag`? – GSerg Sep 27 '16 at 18:43
  • 1
    any reason why you're not using `@Html.DropDownListFor`? – JamieD77 Sep 27 '16 at 18:47
  • @JamieD77 I figured this out. I posted my answer – Grizzly Sep 27 '16 at 18:51
  • @GSerg I figured this out. I posted my answer – Grizzly Sep 27 '16 at 18:51
  • 1
    Here is a solution which does not use ViewBag, but use a view model and `DropDownListFor` helper method. [What is the best ways to bind @Html.DropDownListFor in ASP.NET MVC5?](http://stackoverflow.com/questions/39550804/what-is-the-best-ways-to-bind-html-dropdownlistfor-in-asp-net-mvc5) – Shyju Sep 27 '16 at 18:53

1 Answers1

1

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.

Grizzly
  • 5,873
  • 8
  • 56
  • 109
  • Terrible solution (no strong binding, no validation etc). Bind to your model. Refer also [Will there be any conflict if i specify the viewBag name to be equal to the model property name](http://stackoverflow.com/questions/37161202/will-there-be-any-conflict-if-i-specify-the-viewbag-name-to-be-equal-to-the-mode/37162557#37162557) –  Sep 27 '16 at 21:52