Shawn
Shawn

Reputation: 509

Unable to save Enum values into entity field from DropDownList - EF Code First MVC3

I have a DropDownList that contains the correct items and values when the view is rendered but the selected value is not being saved within the designated entity field Garage. Currently the value being saved and returned is 0 (None) in both create or edit post methods. I'm sure this is something simple but I can't figure it out... Thanks in advance!

The Model Class:

public enum GarageType { None = 0, One = 1, Two = 2, Three = 3, Four = 4 }

public int Garage { get; set; }

[NotMapped]
public GarageType GarageEnumValue
{
    get { return (GarageType)Garage; }
    set{ Garage = (int)value; }
}

The Control Create and Edit methods both look like this:

var statuses = from Property.GarageType s in Enum.GetValues(typeof(Property.GarageType))
                       select new { ID = (int)s, Name = s.ToString() };
ViewBag.GarageId = new SelectList(statuses, "ID", "Name", statuses.FirstOrDefault().ID);

Last the View:

@Html.DropDownList("GarageId", String.Empty)

Upvotes: 2

Views: 1791

Answers (1)

Eranga
Eranga

Reputation: 32437

Use the following overload of DropDownList method

@Html.DropDownList("GarageEnumValue", (SelectList)ViewBag.GarageId, String.Empty)

If you have a strongly type model use

@Html.DropDownListFor(m => m.GarageEnumValue, (SelectList)ViewBag.GarageId, String.Empty)

The first argument in both cases should be the property that you are going to bind the list.

Upvotes: 2

Related Questions