Brian David Berman
Brian David Berman

Reputation: 7684

DropDownListFor from Enum with default value using ViewModel

How would I configure my ViewModel and View to support a dropdown list that contained the following Enum:

public enum PersonType
{
   Bride,
   Groom
}

I would want the text of the dropdown to show "Bride", "Groom" and the value to be 0 and 1 respectively. I would want to configure a default (either Bride or Groom) for the View as well. The purpose of this is for a "Create" form that I would post and later determine which option was selected (I'm guessing I would need an int within my ViewModel to track what the user selected). How would this get wired up? I'm using Razor.

Upvotes: 2

Views: 4029

Answers (2)

Rafay
Rafay

Reputation: 31033

public enum PersonType
{
   Bride=0,
   Groom=1
}

in your model you will have a property like

public class mymodel{

[Required(ErrorMessage="this field is required")]
public int ID{get;set;}
public IEnumerable<KeyValuePair<string, string>> _list{get;set}
}

in your controller

mymodel model = new mymodel();

model._list=Enum.GetNames(typeof(PersonType))
             .Select(x => new KeyValuePair<string, string>(x, x.ToString()));
return View(model);

and in your view

@Html.DropDownListFor(x=>x.ID,new SelectList(model._list,"key","value"))
@ValidationMessageFor(x=>x.ID)

Upvotes: 4

StanK
StanK

Reputation: 4770

I have created a HtmlHelper for enums - and set up a default string template to use that helper if the Model type is an enum.

This means that I can just go @Html.EnumDropDownListFor( x => x.PersonType ) and it will render a drop down list with the enum options.

I copied the helper from this blog, and added the following to the string template in \Shared\EditorTemplates\String.cshtml

@model object
@if (Model is Enum)
{
    @Html.EnumDropDownListFor(x => x)
}
else
{
    @Html.TextBoxFor(x => x)
}

This means that I will get a dropdown list for any enum, without worrying about changing the view model.

The helper doesn't set the values of the select box to the underlying number, but it still binds to the action parameters fine. You should be able to editor the helper fairly easily of having the underlying number as part of the dropdown list easily enough.

Upvotes: 1

Related Questions