Search code examples
asp.netasp.net-mvchtml-helper

Having problems with a model provided placeholder for dropdown


So I have two cases that work independantly.

If I know I have model data in the dropdown, I use this code.

        @Html.DropDownListFor(model => model.CarID, (SelectList)ViewBag.Cars, htmlAttributes: new { @class = "form-control" })

HOWEVER, the problem with this, if CarID is null the first item on the list will be the pre selected in the dropdown.

And in another form, I use this one:

@Html.DropDownListFor(model => model.CarID, "--Select a Car--", (SelectList)ViewBag.Cars, htmlAttributes: new { @class = "form-control" })

My Controller has this to provide the view data:

    ViewBag.Cars = new SelectList(db.Units, "CarID", "Name", model.CarID);

Is there ONE of these that I can use where it will have a placeholder ONLY if model data is not present to fill the spot?


Solution

  • In your second approach, you are using the helper method incorrectly,

    It should be

    @Html.DropDownListFor(model => model.CarID,(SelectList)ViewBag.Cars,
                                               "Select one", new { @class = "form-control" })
    

    This will render the dropdown with a "Select one" option as the first (and default item), if nothing is pre selected (model.CarID is null). If Model.CarID has a valid value, It will select the corresponding option.

    If you absolutely want to remove the "Select one" when Model.CarID is not null, you can write some javascript which executes on the document load (jQuery document ready :) ) to check the selected option and remove it as needed.