Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
748 views
in Technique[技术] by (71.8m points)

c# - Html.EnumDropdownListFor: Showing a default text

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"})

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 enter image description here 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: The image is the screenshot of the page when it loads. By default it'll show Trial as selected option.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...