MVC Dropdownlist for enum

If you wanna display a dropdown list for an enumeration. ASP.NET MVC – Creating a DropDownList helper for enums is a great tutorial to achieve that.

However, if you wanna save in your DB the integer and not the text value, check Best method to store Enum in Database.

I had an enum similar to this:

public enum Sources
{
	Internet = 20,
	Space = 999
}

In my model class, I ended to use this code:

[Required]
[HiddenInput(DisplayValue = false)]
public virtual int SourceId
{
	get
	{
		return (int)this.Source;
	}
	set
	{
		Source = (Sources)value;
	}
}
[EnumDataType(typeof(Sources))]
public Sources Source { get; set; }

Hope this helps.

Leave a Reply

Your email address will not be published. Required fields are marked *