Cannot find a way to add a placeholder for an MVC

2019-04-26 15:07发布

问题:

I've tried searching the web and trying out different things with my code. I know how to add a placeholder for a textbox, but how about adding one for an MVC 5 dropdownlistfor?

I have the following code, but will not put the placeholder in the dropdownlist.

@Html.DropDownListFor(model => model.CustomerID, new SelectList(ViewBag.Customers, "CustomerID", "Email", null, new { htmlAttributes = new { @class = "form-control", @placeholder = "-Select-" } }))

What would be the syntax I would need to accomplish this?

回答1:

Try this:

@Html.DropDownListFor(model => model.CustomerID, 
    new SelectList(ViewBag.Customers, "CustomerID", "Email"), 
    "-- Please Select --", 
    new { htmlAttributes = new { @class = "form-control" } })

3rd overload can be the "placeholder" (optionLabel).

A select box doesnt have a "placeholder" like text inputs do.