MVC4 DropDownListFor Object reference not set to an instance of an object

JasonH picture JasonH · Feb 2, 2014 · Viewed 11.3k times · Source

I'm about to go mad trying to figure this out. I'm newer to MVC but have become pretty comfortable with it.

I am trying to place a Dropdown List on a View but keep getting "Object reference not set to an instance of an object" on the line that is calling the DropDownListFor. Here's what I have:

Model

public class UserModel
{
    public class DietObject
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

    public IEnumerable<DietObject> DietOptions = new List<DietObject>
    {
        new DietObject { Id = 0, Name = "Meat" },
        new DietObject { Id = 1, Name = "Vegetarian" }
    };

    [Required]
    [StringLength(15)]
    [Display(Name = "Diet:")]
    public string Diet { get; set; }
}

Controller

    [HttpGet]
    public ActionResult Registration()
    {
        return View();
    }

View

    <div class="fHeader">
        <%: Html.LabelFor(m => m.Diet) %>
    </div>
    <div class="fText">
        <%: Html.DropDownListFor(m => m.Diet, new SelectList(Model.DietOptions, "Id", "Name", Model.DietOptions.First().Id))%>
        <%: Html.ValidationMessageFor(m => m.Diet)%>
    </div>

Error

During the load of the page, it errors on this line:

<%: Html.DropDownListFor(m => m.Diet, new SelectList(Model.DietOptions, "Id", "Name", Model.DietOptions.First().Id))%>

Someone put me out of my misery. Much appreciated.

Answer

nemesv picture nemesv · Feb 2, 2014

If you want to directly access the Model property in your view (in this case writing Model.DietOptions) then you need to pass in a model instance when calling View in your controller:

[HttpGet]
public ActionResult Registration()
{
    return View(new UserModel());
}

Otherwise the Model will be null and you will get a nullrefence excpetion.