asp.net - Razor 页面部分 View : Model is not defined

标签 asp.net asp.net-core razor-pages

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/

相关文章:

asp.net - 为什么我的隐藏输入写的是: value ="value" instead of true/false?

asp.net - 使用AWS计划任务

c# - asp.net 正常 html 输入 runat ="server"在代码隐藏中返回未更新的值

c# - .NET Core 中 Assembly.GetEntryAssembly() 的等价物是什么?

asp.net-core - 在开发中的 ASP.NET Core 项目上启用/禁用 SSL

asp.net-core - 如何用 Razor Pages 路由替换 MVC HomeController/Index 重定向?

asp.net - 如何在不打开弹出窗口的情况下打印网页?

c# - 使用 gatsby 和 aspnet 提供多个索引文件

c# - ViewData 未传递到 ASP.NET Core 2.1 中的布局

asp.net-core - ASP.NET 核心 2.2。 Razor Pages - 如何根据另一个字段填充表单控件