ASP.NET MVC DropDownListFor exception

If you create a basic view model with some data you wish to present in an HTML select list you might proceed as follows by using the C# 3.0 feature of automatic properties:

public class Agent {
  public int SelectedOfficeId { get; set; }
  public IEnumerable<SelectListItem> OfficeItems { get; set; }
}

Then in your Razor view markup:

@model ViewModels.Agent
@Html.DropDownListFor(m => m.SelectedOfficeId, Model.OfficeItems)

Now you move on to your controller just to check if all this is working:

var model = new ViewModels.Agent();
return View(model);

Well you will get this exception:
The ViewData item that has the key ‘SelectedOfficeId’ is of type ‘System.Int32’ but must be of type ‘IEnumerable<SelectListItem>’.

DropDownListForException

The problem is your collection of list items is null

In a real app you would have some mapping code that populated your view model anyway but with the exception not being intuitive debugging is difficult.

Another solution is to hand craft your properties to protect against this:

public class Agent
{
    private IEnumerable<SelectListItem> _offices;

    public int SelectedOfficeId { get; set; }
    public IEnumerable<SelectListItem> OfficeItems
    {
        get
        {
            return _offices ?? new List<SelectListItem>();
        }
        set
        {
            _offices = value;
        }
    }
  }

What do you think?

Good related references:

  1. DropDownListFor with ASP.NET MVC on Ode To code by K. Scott Allen
  2. C# 3.0 Auto Properties discussion