Tarta
Tarta

Reputation: 2063

Controller doesn't update Razor view model: how to pass value to a view

I am trying to set up a simple web page build with Razor and .net Core.

My controller:

[HttpGet("/api/employees")]

public ActionResult Index()
{
    MyPaginationModel aux = new MyPaginationModel();
    aux.Employees = new List<EmployeeViewModel> {
    new EmployeeViewModel{
        Name = "Test",
        Surname = "Test",
        }
    };
    return View(aux);
}

my view:

@page


@model MyPaginationModel

<table class="table table-striped">
    @foreach (var item in Model.Employees)
    {
        <tr>
            <td>@item.Name</td>
            <td>@item.Surname</td>
        </tr>
    }
</table>

MyPaginationModel:

public class MyPaginationModel : PageModel
{
    public List<EmployeeViewModel> Employees { get; set; }
}

And EmployeeViewModel:

public class EmployeeViewModel
{
    public string Name { get; set; }
    public string Surname { get; set; }
}

It complaints about a nullreferencepointexception at Model.Employees . So, somehow I need to pass the instance I created in the controller to the view.

Upvotes: 0

Views: 414

Answers (1)

XAMT
XAMT

Reputation: 1627

Because @page directive makes the view into an MVC action. It means that it handles requests directly, without going through a controller.

More info : Razor Pages in ASP.NET Core

Solution:

  1. Remove : @page

  2. Add : @using MyPaginationModel Namespace

Upvotes: 2

Related Questions