skip to Main Content

I’ve created an ASP.NET Core 6 MVC project, and I want to see "Test" when i request it but I’m getting NullReferenceException. But when I create the Razor pages application and try the same thing on that project, I don’t get any errors.

I run app on Ubuntu 22.04, I use .NET Core 6.0 Framework.

namespace MyApp.Namespace
{
    public class TestModel : PageModel
    {
        public string? Message { get; set; }
        
        public void OnGet()
        {
            Message = "Test";
        }
    }
}

View:

@model MyApp.Namespace.TestModel

<dir>@Model.Message</dir>

Exception:

NullReferenceException: Object reference not set to an instance of an object.

AspNetCoreGeneratedDocument.Views_Home_Test.ExecuteAsync() in Test.cshtml

@Model.Message

I tried to change namespaces and add a @page directive in Razor page. Nothing has changed.

2

Answers


  1. According to the code above you should make the following declaration in the Razor view file:

    @page
    @using MyApp.Namespace
    @model TestModel 
    
    <dir>@Model.Message</dir>
    

    Detailed instructions on how to create a Razor Pages and @page, @model declarations you can find in the Microsoft documentation here: Razor Pages

    Login or Signup to reply.
  2. MVC needs to pass model between View and controller. When you want to show values from backend, you need to return view with models.

    create a model to pass data:

     public class TestModel
        {
            public string? Message { get; set; }
        }
    

    set the default value in http get action:

    public IActionResult Index()
            {
                
                TestModel test = new TestModel();
                test.Message = "Test";
    
                //return view with model
                return View(test);
            }
    

    View

    @model TestModel
    
    <h1>@Model.Message</h1>
    

    Now you can show Test in your view:

    enter image description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search