Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possible to give Html.DropDownListFor() option label a value?

I have this

 @Html.DropDownListFor(x => x.Names, new SelectList(Model.Names, "Value", "Text"), "---Filter By Name---", new { @class = "nameSelecter" })

When this renders "---Filter By Name---" will be the first choice. I am wondering can I set a value for this?

<option value="">---Filter By Name---</option>

Right now it has no value. I would like to give one.

like image 453
chobo2 Avatar asked Feb 24 '23 13:02

chobo2


2 Answers

The DropDownListFor doesn't support this. You will need to write a custom helper or do it with javascript. This being said setting a value for the default choice wouldn't make sense as it will also break validation logic for required properties.

like image 149
Darin Dimitrov Avatar answered Feb 27 '23 05:02

Darin Dimitrov


I can think of a reason for wanting to be able to do this. I am being confronted with it now. But, as always there may be another way. I do not want selection to be required because the resulting "empty value" (or 0) value has special significance, does not conflict with other values and can be acted upon by intended for such a special, though artificially induced case.

I am using EF and I have an either/or by which valid dropdown selection yields a key for a related entity in a complex model. When a zero value is entered the expectation is that the related entity bound controls are rendered and thereby are validated. When a non-zero value is entered it represents a key value therefore the related entity controls are not rendered and it is enough for the parent entity to posess an existing key value...not needing the actual bound values required to create the new child entity.

like image 40
Pat Pattillo Avatar answered Feb 27 '23 05:02

Pat Pattillo