Skip to content

Instantly share code, notes, and snippets.

@ferventcoder
Created April 4, 2012 19:04
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ferventcoder/2304804 to your computer and use it in GitHub Desktop.
Save ferventcoder/2304804 to your computer and use it in GitHub Desktop.
MVC Html DropDownListHelper
public static class EnumerationExtensions
{
public static IEnumerable<SelectListItem> GetEnumerationItems(this Enum enumeration)
{
var listItems = Enum
.GetValues(enumeration.GetType())
.OfType<Enum>()
.Select(e =>
new SelectListItem()
{
Text = e.GetDescriptionOrValue(),
Value = e.ToString(),
Selected = e.Equals(enumeration)
});
return listItems;
}
}
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
namespace SomeMvcProject.Web.Models
{
public class RegistrationModel : IModel
{
[Required]
[Display(Name = "Position")]
public PositionType Position { get; set; }
}
}
public enum PositionType
{
[Description("Shop Owner")]
ShopOwner,
Member,
Associate
}
<div class="editor-label">
@Html.LabelFor(model => model.Position)
</div>
<div class="editor-field">
@Html.DropDownListFor(m => m.Position, Model.Position.GetEnumerationItems())
@Html.ValidationMessageFor(model => model.Position)
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment