user793468
user793468

Reputation: 4966

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.Model = 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>

Upvotes: 2

Views: 3340

Answers (4)

RickAndMSFT
RickAndMSFT

Reputation: 22770

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.

Upvotes: 1

Chase Florell
Chase Florell

Reputation: 47367

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>

<% } %>

Upvotes: 1

brodie
brodie

Reputation: 5424

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

Upvotes: 0

Joe Enos
Joe Enos

Reputation: 40393

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.

Upvotes: 0

Related Questions