2

I am trying to create a drop down list using asp.net mvc.

Model:

    public string Status { get; set; }

    public List<SelectListItem> StatusList { get; set; }

    public AddUser()
    {
        StatusList = new List<SelectListItem>
                         {
                             new SelectListItem{Value = "0",Text = "0"},
                             new SelectListItem{Value = "1",Text = "1"}
                         };
    }

View:

<%: Html.DropDownListFor(m=>m.Status,new SelectList(Model.StatusList,"Value","Text")) %>
<%: Html.ValidationMessageFor(m => m.Status) %>

I don't know why but I keep getting this error:

Object reference not set to an instance of an object.

Anyone knows what I am doing wrong?

tereško
  • 58,060
  • 25
  • 98
  • 150
Houa Lee
  • 23
  • 1
  • 3
  • Are you sure you are instantiating StatusList by calling AddUser? Is the correct model being used in the view? Is the view being passed in by the controller? – Travis J Mar 23 '12 at 23:45
  • Why in the world are you using `new SelectList(Model.StatusList,"Value","Text")` - `StatusList` is already `IEnumerable` - your just creating an identical `IEnumerable` from the first one - its just `Html.DropDownListFor(m => m.Status, Model.StatusList)` –  Jan 11 '17 at 12:00

2 Answers2

1

This error usually happens when you leave a field of model null or the model is null

Make sure that "Status" isn't null and your return the model in "View" just like this:

    //end of an action code
    AddUser model = new AddUser();

    model.Status = "0"; //status can't be null (cause the the exception cited earlier)

    return View(model);  //if you do not pass the model as argument the model will be null in view
}

And one more tip for u:
The class SelectList implements IEnumerable<SelectListItem> so in view your code may look something like this:

<%: Html.DropDownListFor(m=>m.Status, Model.StatusList) %>
<%: Html.ValidationMessageFor(m => m.Status) %>

You don't need instantiate again.

Jonny Piazzi
  • 3,684
  • 4
  • 34
  • 81
  • Yeah, I didn't pass the model to the view. Was still to new to ASP.NET MVC. Such a simple mistake. Thanks for the help. – Houa Lee Sep 14 '12 at 17:44
0

I think Travis is right, you've forgot install StatusList, maybe it's null.

Anton
  • 1,583
  • 12
  • 17