-1

I have a drop down list on my view that for some reason doesn't display the selected value no matter what I've been trying, although I can use it to choose values and update the database with them with no problem.

VIEW

So on the view I have the following code to display the field

@Html.DropDownListFor(model => model.FormType, ViewBag.FormType as SelectList, new { @class = "form-control" })

The "ViewBag.FormType" is created in the controller from a SelectList object that i'm then passing in using a viewbag object.

CONTROLLER

I'm using some code to generate the selectlist and then choose the selected value from the value in the database for that record. It's here where i'm thinking that the problem is

    short FormType = 0;

    if (account?.FormType != null)
    {
        FormType = (short)account.FormType;
    }

    var FormTypeList = new SelectList(
        new List<object>
            {
                new {value = "0", text = "Please Select..."},
                new {value = "1", text = "Full"},
                new {value = "2", text = "Short"}
            }, "value", "text", FormType);


    ViewBag.FormType = FormTypeList;

At first I thought that the problem was that the value in the database was a numerical value and the "value" in the selectlist was a text, so i've tried switching them both from one to the other and it's not helped. In the example that i'm working with the value in the database is 2.

I'm very lost to what the problem could be so any help would be appreciated.

James Peel
  • 159
  • 1
  • 3
  • 11
  • And just use `ViewBag.FormTypeList = new List{ new SelectListItem { Value = "1", Text = "Full" }, new SelectListItem { Value = "2", Text = "Short" } };` and do not add the 1st option. Add it using `@Html.DropDownListFor(model => model.FormType, (IEnumerable)ViewBag.FormTypeList, "Please Select...", new { @class = "form-control" })` so it correctly generates the label option with a `null` value. –  Feb 10 '18 at 04:34

1 Answers1

1
@Html.DropDownList("FormType", null, "Select", htmlAttributes: new { @class = "form-control" })
Amal Sebastian
  • 193
  • 3
  • 19