【发布时间】: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 => model.EmployeeDetail.DateOfBirth)替换@Html.ValidationMessageFor(model => @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