0

我的观点

<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>

我的控制器动作

        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);
    }

我的视图模型

public class UserViewModel
{
    public EmployeeDetail EmployeeDetail { get; set; }
}

我的模型

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; }
}

在我看来,我在 @Html.ValidationMessageFor(model => @Model.EmployeeDetail.DateOfBirth) 获得对象引用

由于我从控制器操作传递给视图的视图模型“emp”为空,因此我收到此错误,因为我在数据库中没有该特定 ID 的任何数据。

如何避免此对象引用错误。

4

1 回答 1

1

代替

 @Html.EditorFor(model => @Model.EmployeeDetail.DateOfBirth)

采用

 @Html.EditorFor(model => model.EmployeeDetail.DateOfBirth)

你应该对所有线路都这样做......

 @Html.SomethingFor(model => model.EmployeeDetail.Something) // Not @Model.Something

更新:

不要让 EmployeeDetail 为空。

public class UserViewModel
{
     private EmployeeDetail _employeeDetail = new EmployeeDetail();

     public EmployeeDetail EmployeeDetail 
     { 
        get { return _employeeDetail; }
        set { _employeeDetail = value ?? new EmployeeDetail(); } 
     }
}
于 2013-02-04T12:34:27.270 回答