Search code examples
c#asp.net-core-mvcrazor-pagescode-behind

How to correctly set up 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 into two using a 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 error:

'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

  • 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.

    You are getting the exception because of your incorrect reference on your view: @model SportData.Web.Views.Home.Index

    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>
    

    enter image description here

    You can get more details here in this link

    Output:

    enter image description here

    Note: If you need more implementation samples, you can check the official documentation