Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 283
JasonH Avatar asked Feb 02 '14 06:02

JasonH


1 Answers

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.

like image 188
nemesv Avatar answered Nov 16 '22 16:11

nemesv