ASP MVC错误:对象引用未设置为对象的实例

时间:2013-02-04 12:33:14

标签: asp.net-mvc asp.net-mvc-3 asp.net-mvc-4

我的观点

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

我的viewmodel

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 =&gt; @ Model.EmployeeDetail.DateOfBirth)获得对象参考

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

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

1 个答案:

答案 0 :(得分: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(); } 
     }
}