Reputation: 11221
TLDR: the problem is, I see the following error when I try to get ID from Model (line 8. of below code):
System.NullReferenceException: Object reference not set to an instance of an object.
Details:
I wanted to make part of my HTML reusable. There is a large div called "InfoBox" that contains some information, which is placed in multiple locations on my website. I decided to create Partial Razor Page. Here is how I made it:
_TextBoxInfoPartial.cshtml.cs
:
public class _TextBoxInfoPartialModel : PageModel
{
[BindProperty]
public string ID { get; set; }
public IActionResult OnGet()
{
ID = ""; //default
return Page();
}
}
_TextBoxInfoPartial.cshtml
:
@page
@model Definicje.Pages.Shared._TextBoxInfoPartialModel
<button type="button" class="visibility-toggler" visibility-toggler="#hint-math@(Model.ID)">Wstaw wzór</button>
<div id="hint-math@(Model.ID)" class="hintbox">
some text
</div>
To place partial in another cshtml file, I use this line:
@await Html.PartialAsync("_TextBoxInfoPartial", new _TextBoxInfoPartialModel { ID = g.ID + "" })
I don't understand. I'm specifying Model for Partial, why is it undefined then?
Upvotes: 2
Views: 2345
Reputation: 218892
For the partial view, Remove the @page
directive.
@model Definicje.Pages.Shared._TextBoxInfoPartialModel
<button type="button" class="visibility-toggler"
visibility-toggler="#hint-math@(Model.ID)">Wstaw wzór</button>
<div id="hint-math@(Model.ID)" class="hintbox">
some text
</div>
Now Model
will be the _TextBoxInfoPartialModel
object you are passing from the other view.
When you add the @page
directive to the view file, it starts to behave differently, more like an action method - you can access it via an http request.
Another observation is, if your file name starts with _
prefix, the routing capability mentioned above will not work. It cannot be directly accessed by an Http request.
So for your partial views, do not use @page
directive
Upvotes: 2