C# – Html.EnumDropdownListFor: Showing a default text

asp.net-mvcasp.net-mvc-5.1cdrop-down-menu

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.

Best Answer

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)