My view
<table>
<tr>
<td>
Middle Name :
</td>
<td>
@Html.EditorFor(model => @Model.EmployeeDetail.MiddleName)
</td>
<td>
@Html.ValidationMessageFor(model => @Model.EmployeeDetail.MiddleName)
</td>
</tr>
<tr>
<td>
Last Name :
</td>
<td>
@Html.EditorFor(model => @Model.EmployeeDetail.LastName)
</td>
<td>
@Html.ValidationMessageFor(model => @Model.EmployeeDetail.LastName)
</td>
</tr>
<tr>
<td>
Date of Birth :
</td>
<td>
@Html.EditorFor(model => @Model.EmployeeDetail.DateOfBirth)
</td>
<td>
@Html.ValidationMessageFor(model => @Model.EmployeeDetail.DateOfBirth)
</td>
</tr>
</table>
My Controller action
public ActionResult Index()
{
var id = 0;
if (Session["id"] != null)
{
id = Convert.ToInt32((Session["id"].ToString()));
}
var empDetails = _empRepository.GetEmployeeDetails(id);
var emp = new UserViewModel { EmployeeDetail = empDetails };
return View(emp);
}
My viewmodel
public class UserViewModel
{
public EmployeeDetail EmployeeDetail { get; set; }
}
my model
public partial class EmployeeDetail
{
public int Id { get; set; }
public int UserId { get; set; }
public System.DateTime DateOfBirth { get; set; }
public string IsAdmin { get; set; }
}
In my view I am getting object reference at @Html.ValidationMessageFor(model => @Model.EmployeeDetail.DateOfBirth)
I am getting this error due to viewmodel “emp” which I am passing to view from controller action is null as I dont have any data in database for that particular Id.
How can I avoid this object reference error.
Instead of
use
You should do it for all lines…
UPDATE:
Don’t let EmployeeDetail to be null.