Html.EnumDropdownListFor:显示默认文本 [英] Html.EnumDropdownListFor: Showing a default text

查看:455
本文介绍了Html.EnumDropdownListFor:显示默认文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我看来,我有一个枚举列表(Asp中的一个新功能.Net MVC 5.1)。

In my view I have a enumdropdownlist (a new feature in Asp.Net MVC 5.1).

@Html.EnumDropDownListFor(m => m.SelectedLicense,new { @class="form-control"})

如果我执行上面的代码,我得到下面的枚举的下拉列表。 p>

If I execute the above code I get dropdownlist for my following enum.

public enum LicenseTypes
{
    Trial = 0,
    Paid = 1
}

但默认情况下,我希望我的下拉列表有一个值(自定义文本)
,是我尝试的

but by default I want my dropdownlist to have a value(custom text) and this is what I tried

@Html.EnumDropDownListFor(m => m.SelectedLicense,"Select a license" ,new { @class="form-control"})

但现在问题是我运行它的时候,我的下拉列表看起来像这样

所以,我想显示的默认文本默认情况下不会显示。
如果用户选择选择许可证并尝试提交表单,则会显示选择许可证的错误,但不会显示为默认文本。
我需要改变什么?

but now the problem is when i run it, my dropdownlist looks like this So, the default text I want to show doesn't appear by default. If a user selects "select a license" and tries to submit the form, it does show an error saying "select a license" but it doesn't show as default text. Something i need to change?

Ps:图像是加载页面的截图。默认情况下会显示为试用选项。

Ps: The image is the screenshot of the page when it loads. By default it'll show Trial as selected option.

推荐答案

尝试更改索引 LicenseTypes 1开始 0 如下所示:

Try to change the Index of LicenseTypes start from 1 not 0 like below:

public enum LicenseTypes
{
    Trial = 1,
    Paid = 2
}

然后你可以使用 Range属性验证所选许可证类型,如下所示:

Then you can use Range attribute to validate the selected license type like below:

public class YourViewModel
{
     //Other properties
     [Range(1,int.MaxValue,ErrorMessage = "Select a correct license")]
     public LicenseTypes LicenseTypes { get; set; }
}

最后,在您的看法中:

   @Html.EnumDropDownListFor(m => m.LicenseTypes,"Select a license",new { @class = "form-control"})
   @Html.ValidationMessageFor(m => m.LicenseTypes)

这篇关于Html.EnumDropdownListFor:显示默认文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆