Is it possible to assign an Html.DropDownListFor () value to a value?

I have it

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

When it displays "--- Filter by name ---", this will be the first choice. I am wondering if I can set a value for this?

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

Now it does not matter. I would like to give one.

+4
source share
2 answers

DropDownListFor does not support this. You will need to write a custom helper or do it using javascript. This suggests that setting the default value for the selection does not make sense, since it also violates the logic of checking the required properties.

+7
source

I can come up with a reason to be able to do this. Now I come across this. But, as always, there could be another way. I do not want the choice to be required, because the obtained value of "empty value" (or 0) has a special meaning, does not contradict other values ​​and can be used for such a special, albeit artificially caused case.

I use EF, and I have either /, or by which a valid dropdown gives the key for a related object in a complex model. When a null value is entered, the expectation is that related items are bound to related objects that are visualized and thus checked. When a nonzero value is entered, it is the key value, so the associated object controls are not displayed, and for the parent object, it is enough to have the existing key value ... without requiring the actual binding values ​​needed to create a new child element of the object.

+1
source

Source: https://habr.com/ru/post/1347394/


All Articles