简体   繁体   中英

Setup correctly a razor page to have access to data in code-behind

I'm new with Razor Pages and I found out that code can be divided using code-behind file. So I created this Index class to initialize my date and print them to the .cshtml file. But when I try to compile and run it, I get an reror

'Object reference not set to an instance of an object.'

when I try to use @Model.date .

I understood that the variable are not initialized cause OnGet method is never called. But it should be called when the page is requested right?So why variable are never initialize? I start the project in localhost with visual studio so i want only to print the data. First of all, when I put the code inside the Razor page without using the class Index it worked as I expected. When I tried to move to the next step in the learning path, I am just stuck.

@page
@model SportData.Web.Views.Home.Index

<div class="date">
    <h1>Aggiornamento lista in data @Model.date</h1> --> error here
 
</div>
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace SportData.Web.Views.Home
{
    public class Index : PageModel
    {
        List<string> months = new List<string>();
        public DateTime date { get; set; }

        public int num = 4; --> also this give the same error if i try to put in the h1 tag
        public DateTime specificDate { get; set; }
         
        public void OnGet() {
            date = DateTime.Now;
            specificDate = new DateTime(2022, 08, 01);
        }
    }
}

with debug: link to screen of debug result

[SOLUTION]: At the end, the problem was that i create an ASP.NET Web (MVC) project and i tried to implement Razor pattern inside it. So, i understood that is not what i had to do, but simplest way to interact with a Razor Pages in an MVC project is by the Controller and not via Model created as code-beheind.

If anyone else want to put other information about MVC and Razor is well accepted. Thanks.

So I created this Index class to initialize my date and print them to the.cshtml file. But when I try to compile and run it, I get an error "'Object reference not set to an instance of an object." . When I tried to move to the next step in the learning path, I am just stuck.

Well, you are getting the exception bcause of your incorrect reference on your view @model SportData.Web.Views.Home.Index

Solution:

You should use your reference as @model Index so your view should be as following:

@page
@model Index

<div class="date">
    <h1>Aggiornamento lista in data @Model.date</h1>
 
</div>

在此处输入图像描述

You can get more details here

Output:

在此处输入图像描述

Note:

If you need more implementation sample, you can check our official document here.

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