Html.EnumDropdownListFor: Showing a default text
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)
ASP MVC 5 @Html.EnumDropDownListFor Defaults to first Item
The solution for this is to make the model enum property a nullable type:
public class MyViewModel
{
public string searchTerm { get; set; }
public EmploymentType? EmploymentType { get; set; }
}
This way the property allows for null entries and by default it will be null.
How to add a default item to an EnumDropDownList in MVC?
Your model property is probably not Nullable
. That means it will always be initialized to the first value of the enum.
If your model property looks like this:
public MyEnum { get; set; }
Change it to this:
[Required] //Require one of the values is selected i.e. value is not null
public Nullable<MyEnum> { get; set; }
This is a very general problem related to requiring value types have a value set. An easy way is to make it Nullable
and check it is not null. As otherwise the value type will just have its default value.
Setting default value to Html.DropDownListFor
If you want to pass default value for the dropdown list than you can do is pass default viewmodel/model with default value
Example :
public ActionResult New()
{
MyViewModel myViewModel = new MyViewModel ();
myViewModel.OfficeAddressCountry = default value;
//Pass it to the view using the `ActionResult`
return ActionResult( myViewModel);
}
or you can try this
var list = new SelectList(Db.Countries, "CountryCode", "CountryName")
list.Add(new SelectListItem(){Value = 1,Text = "Deafult Item",Selected = true };)
ViewBag.ListOfCountries = list;
EnumDropDownListFor with Enum string value
With Andy's anwser, i wrote a helper but not sure it's the best way to do that. If any body have a better solution
public static MvcHtmlString EnumDropDownListWithStringFor<TModel, TEnum>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TEnum>> expression, string optionLabel, object htmlAttributes)
{
var selectListItem = Enum.GetNames(Nullable.GetUnderlyingType(typeof(TEnum))).Select(p => new SelectListItem() { Value = p, Text = p }).ToList();
return SelectExtensions.DropDownListFor(htmlHelper, expression, selectListItem, optionLabel, htmlAttributes);
}
How to set the selected value in EnumDropDownListFor?
As far as I know just make sure the value you want to be selected is set in your Model before you call
//Controller:
...
myModel.TestEnum = TestEnum.name2;
...
//On your view
...
@Html.EnumDropDownListFor(model => model.TestEnum);
...
Related Topics
Add a Package with a Local Package File in 'Dotnet'
Visual Studio Designer in X64 Doesn't Work
How to Store JSON in an Entity Field with Ef Core
Why Re-Initiate the Dbcontext When Using the Entity Framework
Remove the Title Bar in Windows Forms
How to Write Super-Fast File-Streaming Code in C#
Wait for File to Be Freed by Process
Entity-Framework Code Is Slow When Using Include() Many Times
Cookie Confusion with Formsauthentication.Setauthcookie() Method
C#: Triggering an Event When an Object Is Added to a Queue
Changing the Cursor in Wpf Sometimes Works, Sometimes Doesn'T
Jobject.Parse VS JSONconvert.Deserializeobject
How to Find the Fully Qualified Name of an Assembly
Creating Powerpoint Presentations Programmatically
An Expression Tree May Not Contain a Call or Invocation That Uses Optional Arguments
How to Get the Available Wifi Aps and Their Signal Strength in .Net
Enumerating Collections That Are Not Inherently Ienumerable
Need a Way to Reference 2 Different Versions of the Same 3Rd Party Dll