Frage

I'm not grasping some conceptual basics with MVC models and I'm hoping for some helpful clarification.

In my MVC 4 web app, I have a view model that builds an IEnumerable<SelectListItem> for a DropDownList, and if I do this in my view:

@model MyApp.Models.MyModel

@Html.DropDownListFor(x => x.MyThingID, Model.MySelectList, "Select...")

I get an "Object reference not set to an instance of an object" error.

But if I do this:

@model MyApp.Models.MyModel

@{ var myModel = new MyApp.Models.MyModel(); }
@Html.DropDownListFor(x => x.MyThingID, myModel.MySelectList, "Select...")

It works. But this explicit instantiation looks and feels terribly wrong to me, and I'm not sure if I should be doing anything in the controller, which at this point is just a bare-bones "return View()" ActionResult.

I can't find much good guidance and ultimately I'm trying to implement some cascading dropdowns, so I need to get a better grasp on how this works. If you have the time and inclination to assist, I'd greatly appreciate it.

War es hilfreich?

Lösung

You should pass the model to the view. You can do this in the controller code:

return View(myModel);

instead of

return View(); // without the model!

where yourmodel is typeof MyApp.Models.MyModel. Just init it and pass it.

public ActionResult YourAction()
{
    var myModel = new MyApp.Models.MyModel();
    // do other actions or put more data inside myModel
    return View(myModel);
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top