MVC4 DropDownListFor Object reference not set to an instance of an object
Asked Answered
G

1

8

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.

Green answered 2/2, 2014 at 6:27 Comment(1)
FINALLY! I have been messing with this for nearly 7 hours over two days and THIS is the example that finally worked. DropDownListFor is not very friendly. And EF is not something I'm familiar with. This worked great! Saved me having a miserable Friday. Cheers! BTW: I already knew that you had to wire it up. But I couldn't get my example to work until I finally tried the diet example. Awesome.Zak
H
15

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.

Hesiod answered 2/2, 2014 at 6:32 Comment(1)
I get the n00b award of the day, I was overdue. I'll mark as answered when it lets me in a few minutes.Green

© 2022 - 2024 — McMap. All rights reserved.