简体   繁体   中英

.net core 2.2 MVC: Razor Model return null reference exception

I have a very basic project in ASP.NET Core 2.2, the project structure is as the following:

Code layout

The code I am using in Index.cshtml page is as the following:

@page
@using TaskManager.Views.Home
@model IndexModel
<p> Hello @DateTime.Now @Model.test</p>

IndexModel.cs

namespace TaskManager.Views.Home
{
    public class IndexModel : PageModel
    {
        public string test { get; set; }

        public void OnGet()
        {
            test = "IndexModel Test Variable"; 
        }
    }
}

HomeController.cs

namespace TaskManager.Controllers
{
     public class HomeController : Controller
     {
         public IActionResult Index()
         {
             return View();
         }
     }
}

Startup.cs

  public class Startup
  {
      public void ConfigureServices(IServiceCollection services)
      {
          services.AddMvc();
      }

      public void Configure(IApplicationBuilder app, IHostingEnvironment env)
      {
          if (env.IsDevelopment())
          {
              app.UseDeveloperExceptionPage();
          }

          app.UseDefaultFiles();
          app.UseMvcWithDefaultRoute();
       }
   }

Yet I am still getting NullReference exception. What am I doing wrong?

https://i.ibb.co/NL04rgQ/Capture.png

As DavidG points out, you need an instance of your model.

public IActionResult Index(IndexModel indexmodel)
{
    return View(indexmodel);
}

You don't need a Controller with the Razor page, the "cshtml.cs" file that has the "OnGet" also serves as the Model. Your Index model is correct, you don't need the controller for the Razor page. By default going to /Index would pull the "Index.cshtml" in your Pages directory (you can change the default directory in the Configure Services if need be if it's something other than pages) like this:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc().AddRazorPagesOptions(options =>
    {
        options.RootDirectory = "/Content";
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM