Html.EnumDropdownListFor:显示一个默认的文本 [英] Html.EnumDropdownListFor: Showing a default text
问题描述
在我看来,我有一个 enumdropdownlist (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"})
如果我执行上述code为我的下枚举的DropDownList。
If I execute the above code I get dropdownlist for my following enum.
public enum LicenseTypes
{
Trial = 0,
Paid = 1
}
但默认情况下我希望我的我的DropDownList有一个值(自定义文本)
而这也正是我试图
but by default I want my 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"})
但现在的问题是,当我运行它,我的DropDownList的是这样的
因此,默认的文本要显示默认情况下不会出现。
如果用户选择选择一个许可证,并试图提交表单,它只一个错误说选择许可证,但它并不显示为默认文本。
这是我需要改变?
but now the problem is when i run it, my dropdownlist looks like this So, the default text want to show doesn't appear by default. If 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: 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
}
然后你可以使用范围属性
,确认所选的许可证类型如下图所示:
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; }
}
最后,在你看来:
Finally, in your view:
@Html.EnumDropDownListFor(m => m.LicenseTypes,"Select a license",new { @class = "form-control"})
@Html.ValidationMessageFor(m => m.LicenseTypes)
这篇关于Html.EnumDropdownListFor:显示一个默认的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!