I have a simple details view that uses two if statements if the user is a Customer, it displays the customer properties. If the user is an Investor it displays their properties instead.
My issue is that my if statement works for one or the other but not both. Giving me a:
NullReferenceException: Object reference not set to an instance of an object
when trying to use both if statements.
My view
@model MyProject.Models.ApplicationUser
<h3>
@Html.DisplayFor(m => Model.FirstName)
@Html.DisplayFor(m => Model.LastName)
</h3>
@if (Model.Customer.CustomerId != null)
{
<div class="form-group">
<strong>Tax ID:</strong>
@Html.DisplayFor(m => m.Customer.TaxId)
</div>
} else {
}
@if (Model.Investor.InvestorId != null)
{
<div class="form-group">
<strong>Social Security #:</strong>
@Html.DisplayFor(m => m.Investor.SsnNum)
</div>
<div class="form-group">
<strong>Date of birth:</strong>
@Html.DisplayFor(m => m.Investor.DOB)
</div>
} else {
}
Controller
public async Task<IActionResult> Details(string id)
{
if (id == null || id.Trim().Length == 0)
{
return NotFound();
}
var userFromDb = await _db.ApplicationUser.Include(u => u.Investor).Include(u => u.Customer).FirstOrDefaultAsync(i => i.Id == id);
if (userFromDb == null)
{
return NotFound();
}
return View(userFromDb);
}
Investor
public class Investor
{
[Key, ForeignKey("ApplicationUser")]
public string InvestorId { get; set; }
public virtual ApplicationUser ApplicationUser { get; set; }
[Required]
[Display(Name = "SSN")]
public string SsnNum { get; set; }
[Display(Name = "Date of Birth")]
public DateTime DOB { get; set; }
}
CustomerandInvestor. I suspect one of them is not initialized hence you would get NULL reference error.if (Model.Customer.CustomerId != null)haveif (Model.Customer != null && Model.Customer.CustomerId != null).Customeror it's going to have anInvestor, but never both. You should write your conditionals likeModel.Customer != null && Model.Customer.CustomerId != nulllike @WiktorZychla suggested. You can also use the null conditional operator likeModel.Customer?.CustomerId != null, which is a little easier.