ASP.NET Core - MVC - Model variable in view - null exception

Viewed 1828

In an attempt to learn ASP.NET Core MVC I've made a simple project and am trying to pass a model instance created in the controller to the view.

Controller Code - I create a simple list, then pass it to the view, being explicit about which view

public class TableController : Controller
    {
        public IActionResult Index()
        {
            var modelData = new List<string> {"A", "B"};

            ViewBag.Title = "Tables";
            
            return View("/Pages/Table.cshtml", modelData);
        }
    }

View Code

@page
@model List<string>

    <div class="text-center">
        <h1 class="display-4">@ViewBag.Title</h1>

        @if (Model == null)
        {
            <p>There is no data to be displayed</p>
        }
        else
        {
            <ul>
                @foreach (string str in Model)
                {
                    <li>@str</li>
                }
            </ul>
        }
    </div>

When I set a breakpoint in the Controller the object I pass in as the model parameter is not null: enter image description here

However, when I step through into the view code I get this:

enter image description here

I've looked at a few other "Model is null" posts but they were due mismatching types between whats passed in the View() model parameter and whats expected in the view given by the @model declaration.

It's probably something really simple but I'm not sure where I've gone wrong?

2 Answers

I had the same exception, the solution was to remove @page in Index.cshtml and then Boom, everything was there. Took me 5-6 hours to "resolve" this exception but better late, than never.

In asp.net MVC,View does not mean Razor Page.You can use a View page,And add a Table folder in Views.And then add a Index.cshtml(Razor View Page)to it.

Here is a demo worked:

Controller(return View() inIndex action will find a Index.cshtml in Views/Table(Views/ControllerName)):

public class TableController : Controller
    {
        public IActionResult Index()
        {
            var modelData = new List<string> { "A", "B" };

            ViewBag.Title = "Tables";

            return View(modelData);
        }
    }

View(Don't use @page,it's used in Razor Page):

@model List<string>
@{
    ViewData["Title"] = "Table_Index";
}
<div class="text-center">
    <h1 class="display-4">@ViewBag.Title</h1>

    @if (Model == null)
    {
        <p>There is no data to be displayed</p>
    }
    else
    {
        <ul>
            @foreach (string str in Model)
            {
                <li>@str</li>
            }
        </ul>
    }
</div>

Views folder structure(Each folder means a controller except Shared):

enter image description here

Result: enter image description here

Related