Razor Pages 局部视图:模型未定义
Razor Pages Partial View: Model is not defined
TLDR:问题是,当我尝试从模型(以下代码的第 8 行)获取 ID 时看到以下错误:
System.NullReferenceException: Object reference not set to an instance of an object.
详情:
我想让 HTML 的一部分可重复使用。有一个名为 "InfoBox" 的大型 div,其中包含一些信息,它位于我网站的多个位置。我决定创建 Partial Razor Page。这是我的制作方法:
_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>
要将部分内容放在另一个 cshtml 文件中,我使用以下行:
@await Html.PartialAsync("_TextBoxInfoPartial", new _TextBoxInfoPartialModel { ID = g.ID + "" })
我不明白。我正在为部分指定模型,为什么它是未定义的?
对于局部视图,删除 @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>
现在 Model
将成为您从另一个视图传递的 _TextBoxInfoPartialModel
对象。
当您将 @page
指令添加到视图文件时,它的行为开始有所不同,更像是一种操作方法 - 您可以通过 http 请求访问它。
另一个观察是,如果你的文件名以_
前缀开头,上面提到的路由功能将不起作用。它不能通过 Http 请求直接访问。
因此,对于您的局部视图,请勿使用 @page
指令
TLDR:问题是,当我尝试从模型(以下代码的第 8 行)获取 ID 时看到以下错误:
System.NullReferenceException: Object reference not set to an instance of an object.
详情:
我想让 HTML 的一部分可重复使用。有一个名为 "InfoBox" 的大型 div,其中包含一些信息,它位于我网站的多个位置。我决定创建 Partial Razor Page。这是我的制作方法:
_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>
要将部分内容放在另一个 cshtml 文件中,我使用以下行:
@await Html.PartialAsync("_TextBoxInfoPartial", new _TextBoxInfoPartialModel { ID = g.ID + "" })
我不明白。我正在为部分指定模型,为什么它是未定义的?
对于局部视图,删除 @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>
现在 Model
将成为您从另一个视图传递的 _TextBoxInfoPartialModel
对象。
当您将 @page
指令添加到视图文件时,它的行为开始有所不同,更像是一种操作方法 - 您可以通过 http 请求访问它。
另一个观察是,如果你的文件名以_
前缀开头,上面提到的路由功能将不起作用。它不能通过 Http 请求直接访问。
因此,对于您的局部视图,请勿使用 @page
指令