【问题标题】:ASP MVC error: Object reference not set to an instance of an objectASP MVC 错误:对象引用未设置为对象的实例
【发布时间】:2013-01-19 03:53:08
【问题描述】:

我的看法

<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 的任何数据。

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

【问题讨论】:

  • 尝试用@Html.ValidationMessageFor(model =&gt; model.EmployeeDetail.DateOfBirth) 替换@Html.ValidationMessageFor(model =&gt; @Model.EmployeeDetail.DateOfBirth) 并替换其他语法
  • Session["id"] 有效吗?有数据吗?
  • 如果您在emp 中没有任何数据,您可以像这样查看您的视图:if(Model !=null){ //here you write all your view code }else { @: The Model is Empty }
  • 我认为您的会话为空...所以您尝试查找 id=0 的记录
  • 可能_empRepository.GetEmployeeDetails(id); 正在返回null

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


【解决方案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(); } 
     }
}

【讨论】:

    猜你喜欢
    • 2011-06-21
    • 2013-07-26
    • 2011-07-09
    • 2012-08-31
    • 2011-11-21
    • 2012-10-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多