如何从ASP.NET MVC中的枚举中设置dropdownlist中的默认值?
我有这样的性别枚举: 我的enumlist.cs,
public enum Gender
{
[Description("male")]
male= 0,
[Description("female")]
female= 1,
}
但是当它显示在视图中时,我需要下拉以显示---请选择---作为默认值。这样我就可以在jQuery脚本中检查所需的验证。
cteate.html,
<div class="col-xl-4 col-md-6 col-12">
<div class="row">
<div class="col-xl-4 col-md-4 col-12 form-title">
@Html.LabelFor(model => model.Gender)
</div>
<div class="col-xl-8 col-md-8 col-12 form-data">
@Html.DropDownListFor(model => model.Gender, new SelectList(Enum.GetValues(typeof(SubMIS.Models.Gender))), "---Please Select ---", new { @class = "rwd-select" })
@Html.ValidationMessageFor(model => model.Gender)
<label style="color: red">@ViewBag.GenderError</label>
</div>
</div>
</div>
该怎么做?我的代码怎么了?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
用于从
enum
中显示asp.net
的值在助手类中
asp-items =“@html.getEnumSelectList&lt; yourEnumname&gt;
。但是,在代码中,您否则您正在执行此操作,以便您无法使用该格式设置一个格式为设置值,请使用。
>不
[descript> [descript> naber = 2,[description(“ heapen”)]女性= 3,
,以便我可以将默认值设置为1
请参阅下面的默认值:输出:
< img src =“ https://i.sstatic.net/t5pft.gif” alt =“在此处输入图像说明”>
修改枚举:
注意:如果您可以在此处查看,我将
默认枚举
为请选择
,以便在下拉列表
,您无需做任何其他事情。视图:
注意:在这里要记住要记住
“ ---请从您的
,因为这将来自@html.dropdownlistfor中选择---”
enum
。只有这将需要最少修改您要实施的内容。但我更喜欢下面:
输出:
For displaying value from
Enum
inasp.net
has builtin helper class
asp-items="@Html.GetEnumSelectList<YourEnumName>
. However, in your code you are doing otherwise so that you couldn't set a value in that format as setting value usingDropDownListFor
is not supported. Let's move to the solution.Enum:
View:
Note: I have modified the
Enum
value as[Description("male")] male = 2, [Description("female")] female = 3,
so that I could setdefault value as 1
as you can see the default value below:Output:
Work Around To Handle Easily
Modify The Enum:
Note: If you can see here I am setting the the
default enum
asPlease Select
so that it will beassigned value
onDropDownListFor
and you do not need to do anything else.View:
Note: Here point to remember just remove
"---Please Select ---"
from your@Html.DropDownListFor
as this will come from theEnum
. And only this will required least modification what you are trying to implement.But I prefer Like below:
Output: