John McArthur
John McArthur

Reputation: 1024

ASP.NET MVC3 DropDownListFor Enum

Hi I'm fairly new to MVC3 and I'm trying to do something that I think must be fairly common, but can't quite get it.

I have a model I wish store the value for enum DayOfWeek in:

public class Booking
{
    public int ID { get; set; }
    public int Day { get; set; }
    ....
}

I've made it an int to store in the database.

I want to edit in the View as a DropDownList:

    <div class="editor-field">
        @Html.DropDownListFor(model => model.Booking.Day, new SelectList(Enum.GetValues(typeof(DayOfWeek))))
        @Html.ValidationMessageFor(model => model.Booking.Day)
    </div>

However I get the error: "The field day must be a number".

I know I'm missing something, and probably something simple, can anyone help?

Upvotes: 1

Views: 3504

Answers (2)

Massimo Zerbini
Massimo Zerbini

Reputation: 3191

You can also change your model class using DayOfWeek:

public class Booking
{
    public int ID { get; set; }
    public DayOfWeek Day { get; set; }
}

Upvotes: 0

Ben Foster
Ben Foster

Reputation: 34830

Add a SelectList property to your viewmodel and populate as per @Brandon's answer here.

Then you will change your code to:

@Html.DropDownListFor(model => model.Booking.Day, Model.SelectListProperty)

(where SelectListProperty is the name of your property on your viewmodel)

Upvotes: 3

Related Questions