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
According to the code above you should make the following declaration in the Razor view file:
Detailed instructions on how to create a Razor Pages and
@page
,@model
declarations you can find in the Microsoft documentation here: Razor PagesMVC 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:
set the default value in http get action:
View
Now you can show
Test
in your view: