EF5 DropDownListFor for enums

imageLove sharing little gems of knowledge – this is a good one for anyone using Entity Framework 5 and the new’ish enumerations (emums) inclusion in EF5. 

So working on a MVC5 Code First application for a project of my own – and had the following Model.

[sourcecode language='csharp' ]
namespace GeoBucketlist.Model
{
    public enum TagType { Location, Bucketlist, Member }

    public class Tag : Base.Model
    {
        public long Id { get; set; }
        [Required]
        [StringLength(25, ErrorMessageResourceType = typeof(ResourceMessages), ErrorMessageResourceName = "LengthMax25")]
        public string Name { get; set; }        
        public string Description { get; set; }
        public TagType TagType { get; set; }
    }
}
[/sourcecode]

When you auto-create the View templates for editing / adding that model in MVC through T4 templates – the html is as follows follows…

[sourcecode language='html' ]
@Html.LabelFor(model => model.TagType, new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.TagType) @Html.ValidationMessageFor(model => model.TagType)
[/sourcecode]

imageWhich then shows up in your pages as a plain textbox – not a good solution for choosing an enumeration value… 🙁

So simple but elegant solution is to change that line to the following… (Note, would be lovely if this was the default behavior for the @Html.EditorFor – but alas that is a blog article (and more work) for another day – but if anyone else has that complete, always loved to see great code!)

[sourcecode language='html' ]
@Html.LabelFor(model => model.TagType, new { @class = "control-label col-md-2" })
@Html.DropDownListFor(model => model.TagType, new SelectList(Enum.GetValues(typeof(GeoBucketlist.Model.TagType)))) @Html.ValidationMessageFor(model => model.TagType)
[/sourcecode]

Good coding!

//L2

Leave a Reply