简体   繁体   English

可以给Html.DropDownListFor()选项标签一个值吗?

[英]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. 我想给一个。

The DropDownListFor doesn't support this. DropDownListFor不支持此功能。 You will need to write a custom helper or do it with javascript. 您需要编写自定义帮助程序或使用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. 这就是说为默认选择设置一个值是没有意义的,因为它也会破坏所需属性的验证逻辑。

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. 我不希望选择是必需的,因为得到的“空值”(或0)值具有特殊意义,不与其他值冲突,并且可以通过预期用于这种特殊的,虽然是人为诱导的情况。

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. 我正在使用EF,我有一个/或者有效的下拉选择为复杂模型中的相关实体生成一个键。 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. 当输入非零值时,它表示键值,因此不呈现相关实体控件,并且父实体足以拥有现有键值...不需要创建新子项所需的实际绑定值实体。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM