Reputation: 671
I'm getting the error, "Object reference not set to an instance of an object." when attempting to assign a value to a model's fields in my MVC project. My model (not strongly typed) is referenced in my view thus:
...Inherits="System.Web.Mvc.ViewPage<Project.Models.MyModel>" %>
Intellisense picks up MyModel's fields when I access it in the view. My model is posted below:
namespace Project.Models
{
public class MyModel
{
public int AddressId { get; set; }
public int AddressTypeId { get; set; }
....
}
}
As you can see, I do a get set on each field and everything is public. But when I debug it, as soon as I hit anything to do with the Model, the compiler complains that "Object reference not set to an instance of an object."
What's missing here?
Upvotes: 1
Views: 913
Reputation: 4288
You will have to initialize your model first
for eg:
public ActionResult YourAction() { MyModel model = new MyModel(); return View(model); }
Upvotes: 0
Reputation: 1038710
Make sure you have passed a model to this view from the controller action that rendered it:
public ActionResult SomeAction()
{
MyModel model = ... fetch your model from somewhere
return View(model); // <!-- Notice how the model must be passed to the view
}
Obviously the function that is retrieving your model from wherever you are retrieving it must ensure that the model is not null. Alternatively you could test in the view if the model is not null before accessing it's properties and if it is null render some alternative content.
Upvotes: 2