简体   繁体   English

.net core 2.2 MVC:Razor模型返回空引用异常

[英].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: 我在ASP.NET Core 2.2中有一个非常基本的项目,项目结构如下:

Code layout 代码布局

The code I am using in Index.cshtml page is as the following: 我在Index.cshtml页面中使用的代码如下:

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

IndexModel.cs IndexModel.cs

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

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

HomeController.cs HomeController.cs

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

Startup.cs 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. 但是我仍然收到NullReference异常。 What am I doing wrong? 我究竟做错了什么?

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

As DavidG points out, you need an instance of your model. 正如DavidG所指出的,您需要模型的实例。

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. 您不需要带有“剃刀”页面的控制器,带有“ OnGet”的“ cshtml.cs”文件也可以用作模型。 Your Index model is correct, you don't need the controller for the Razor page. 您的Index模型是正确的,您不需要Razor页面的控制器。 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: 默认情况下,转到/ Index会在您的Pages目录中拉出“ Index.cshtml”(如果需要的话,您可以在Configure Services中更改默认目录(如果不是页面的话)),如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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