Stefan
Stefan

Reputation: 585

Rendering a list in a razor view

I have this controller

// GET: Home
        public ActionResult Index()
        {
            List<Users> Users = new List<Models.Users>()
            {
                new Users() {CustomerID = "12", Email = "Email1" },
                new Users() {CustomerID = "22", Email = "Email2" },
                new Users() {CustomerID = "13", Email = "Email3" },
                new Users() {CustomerID = "14", Email = "Email4" },
            };

            return View();
        }

And this view

@model IEnumerable<MB.eXum.Models.Users>   
<h2>Index</h2> 
<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Email)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.CustomerID)
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Email)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.CustomerID)
        </td>
    </tr>
}

When I run the solution I get the error in the code line

@foreach (var item in Model) 

An exception of type 'System.NullReferenceException' occurred in App_Web_index.cshtml.a8d08dba.xeqljjsw.dll but was not handled in user code

What can I do to solve the error?

Upvotes: 0

Views: 1048

Answers (3)

Grizzly
Grizzly

Reputation: 5953

Your View is expecting a collection of Users.

Now in your controller, you are creating Users and are putting them inside a List but then when that is done, you are returning nothing instead of the Collection of Users you just created, hence the NullReferenceException.

View - Creates a ViewResult object that renders a view to the response

Your ViewResult object is your List which you named Users so to get around that error you need to:

return View(Users);

Upvotes: 1

Razvan Dumitru
Razvan Dumitru

Reputation: 12472

In your Razor view, you wait for a list of users, so you must pass that from controller to view.

In razor view you wait for the following list

@model IEnumerable<MB.eXum.Models.Users> 

And in your controller you must pass a list of objects of this type to the view like this

  return View(Users);

where Users is the list that you created.

   List<Users> Users = new List<Models.Users>()
            {
                new Users() {CustomerID = "12", Email = "Email1" },
                new Users() {CustomerID = "22", Email = "Email2" },
                new Users() {CustomerID = "13", Email = "Email3" },
                new Users() {CustomerID = "14", Email = "Email4" },
            };

More about MVC here: http://www.codeproject.com/Articles/54576/Understanding-ASP-NET-MVC-Model-View-Controller-Ar

Upvotes: 1

robasta
robasta

Reputation: 4701

Change your return to include your list, like this:

return View(Users);

Currently, your model will be null.

Upvotes: 1

Related Questions