Null reference exception error
I have a Student data model(Entity Framework) where I have set both "StudentID" and "StudentName" as primary keys. StudentID is of type Int and StudentName is of type String.
I created a strongly-typed view, But when I run it i get the following error:
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Source Error: Line 10: <tr> Line 11: <td> Line 12: <%= Html.Encode(item.StudentID) %>** Line 13: </td> Line 14: <td>
Here is my controller action:
public ActionResult Index()
{
ViewData.M开发者_C百科odel = student.StudentTable;
return View();
}
Here is the View:
<%@ Page
Language="C#"
Inherits="System.Web.Mvc.ViewPage<IEnumerable<Student.Models.StudentTable>>" %>
<html>
<head runat="server">
</head>
<body>
<table>
<% foreach (var item in Model) { %>
<tr>
<td>
<%= Html.Encode(item.StudentID) %>
</td>
<td>
<%= Html.Encode(item.StudentName) %>
</td>
</tr>
<% } %>
</table>
</body>
</html>
Without any additional information, my guess is that item
is null
. If the Student Table has a SINGLE StudentID per record, then you need to simply pass model.StudentID
Controller
public ActionResult Index()
{
var model = student.StudentTable;
return View(model);
}
aspx
<% foreach (var item in Model) { %>
<tr>
<td>
<%= Html.Encode(item.StudentID) %>
</td>
<td>
<%= Html.Encode(item.StudentName) %>
</td>
</tr>
<% } %>
I doubt item is null, if it were null you wouldn't get inside the loop. Set a break point and examine item, it's probably not what you think it is.
If this is the line you're getting the exception on, then your item
variable must be null. You'll need to look closely at how that's being populated - if your model is null, then you should be able to throw a debugger on your controller action and figure out why that's not working.
Could be a few things ...
Are you passing up valid view data from the ActionMethod? Have you defined @model on the view?
Assuming student.StudentTable is a single object with StudentID property then you need to change your view code to Model.StudentID
精彩评论