Introduction
We've all been there - how do I put enumerators into a drop down on a mvc web site? This is how I did it.
The Code
Given the following enumerator defintion:
public enum LocationType { Zipcode=0, City, County, State, Country, Address};
I created the following code. I started off with a base class, allowing me to continue with my chosen technique with additional enumerators:
public abstract class EnumListItem
{
public string Key { get; set; }
public int Value { get; set; }
}
And then inherited my item class from it:
public class LocTypeItem : EnumListItem
{
public LocationType LocType
{
get { return Globals.IntToEnum(this.Value, LocationType.City) ; }
set { this.Value = (int)value; }
}
}
Next, I create a list class, and initialized it in the constructor:
public class LocationTypeList : List<LocTypeItem>
{
public LocationTypeList()
{
this.Add(new LocTypeItem() { Key = "City", LocType = LocationType.City });
this.Add(new LocTypeItem() { Key = "County", LocType = LocationType.County });
this.Add(new LocTypeItem() { Key = "Country", LocType = LocationType.Country });
this.Add(new LocTypeItem() { Key = "State", LocType = LocationType.State });
this.Add(new LocTypeItem() { Key = "Postal Code", LocType = LocationType.Zipcode });
}
}
And finally, I created a static Globals class with a property for the list so I could access it anytime I want, from anywhere I want:
public static partial class Globals
{
public static LocationTypeList ListOfLocationTypes { get; set; }
static Globals()
{
ListOfLocationTypes = new LocationTypeList();
}
public static T IntToEnum<T>(int value, T defaultValue)
{
T enumValue = (Enum.IsDefined(typeof(T), value)) ? (T)(object)value : defaultValue;
return enumValue;
}
}
Using the code
In the view that renders the dropdownlist control, it looks like this:
@Html.DropDownListForEx(model => model.MyIntVar, new SelectList(ViewBag.LocationTypes,"Value","Key"))
Note - The DropDownListForEx method is an extension method that takes car of wrapping the dropdownlist in bootsrap styles and divs. As you can see it really de-clutters the code in your view. One of these days, I'll write an article about these extension methods (I have one for pretty much every standard control you'd see in a MVC app.
Points of Interest
I like to bury complexity as much as is reasonable, so the stuff I need to do all the time is easier.
History
22 Nov 2017 - Forgot to paste the Globals.IntToEnum method in the right place.
21 Nov 2017 - Forgot to include the Globals.IntToEnum method.
18 Nov 2017 - Inital post.