TLDR:问题是,当我尝试从模型获取 ID 时,我看到以下错误(以下代码的第 8 行):
System.NullReferenceException: Object reference not set to an instance of an object.
详细信息:
我想让我的 HTML 的一部分可重用。有一个名为“InfoBox”的大 div,其中包含一些信息,它被放置在我网站上的多个位置。我决定创建部分 Razor 页面。这是我的制作方法:
_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 + "" })
我不明白。我为 Partial 指定 Model,为什么它未定义?
最佳答案
对于部分 View ,删除 @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
将是您从另一个 View 传递的 _TextBoxInfoPartialModel
对象。
当您将 @page
指令添加到 View 文件时,它的行为开始有所不同,更像是一个操作方法 - 您可以通过 http 请求访问它。
另一个观察结果是,如果您的文件名以 _
前缀开头,则上述路由功能将不起作用。不能通过Http请求直接访问。
因此,对于您的部分 View ,请勿使用 @page
指令
关于asp.net - Razor 页面部分 View : Model is not defined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54029251/