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.

有帮助吗?

解决方案

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top