Reputation: 1
I get an exception
Object reference not set to an instance of an object
in ASP.NET MVC when I post form-data with more than one models.
This is my "ViewModel" class:
public class CustomerViewModel
{
public Customer Customer { get; set; }
public IEnumerable<tblGender> Genders { get; set; }
public IEnumerable<tblCountry> Countries { get; set; }
}
This is the Edit
action method:
[HttpGet]
public ActionResult Edit(int id)
{
var customer = _context.Customers
.FirstOrDefault(c => c.Id == id);
var viewModel = new CustomerViewModel()
{
Customer = customer,
Genders = _context.tblGenders.ToList(),
Countries = _context.tblCountries.ToList()
};
return View("Edit",viewModel);
}
[HttpPost]
public ActionResult Edit(Customer customer)
{
var cust = _context.Customers.Single(c => c.Id == customer.Id);
TryUpdateModel(cust);
_context.SaveChanges();
return RedirectToAction("Index", "Customer");
}
Create.cshtml
:
The error occurs in this section
<div class="form-group">
@Html.LabelFor(m => m.Customer.Gender)
@Html.DropDownListFor(m => m.Customer.Gender, new SelectList(Model.Genders, "Id", "GenderName"), "Select Gender", new { @class = "form-control" })
</div>
Upvotes: 0
Views: 48
Reputation: 116
Regarding the Object reference exception. Have you created instances of the objects that you're using? e.g:
private readonly CustomerViewModel _customerViewModel;
_customerViewModel = new CustomerViewModel();
Upvotes: 0
Reputation: 1094
In this piece of code, your variable customer can be null:
var customer = _context.Customers.FirstOrDefault(c => c.Id == id);
In this piece of code, you are assigning that very variable to your model.Customer:
var viewModel = new CustomerViewModel()
{
Customer = customer,
In this piece of code, you are using model.Customer as if you are sure it is not null:
@Html.LabelFor(m => m.Customer.Gender)
Out of many other possibilities, this is the most obvious null-ref I can find. To fix it you can do something like this:
var viewModel = new CustomerViewModel()
{
Customer = customer ?? new Customer(),
or this:
var customer = _context.Customers.FirstOrDefault(c => c.Id == id);
if (customer == null) {
return view("CustomerNotFound"); //or some other way to display your error
}
Upvotes: 2