chobo2
chobo2

Reputation: 85775

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.

Upvotes: 4

Views: 6041

Answers (2)

Pat Pattillo
Pat Pattillo

Reputation: 11

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.

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1038850

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.

Upvotes: 7

Related Questions