局部视图中的模型为空-asp.net核心剃须刀页面

问题描述 投票:0回答:1

我正在使用asp.net core 2.1。

我的主页位于Pages文件夹下,而我的局部视图_test2位于共享文件夹中。这是我的主页:

public class MainModel : PageModel
    {
        public IRepositoryStudent irep;
        public MainModel (IRepositoryStudent _irep){
         irep = _irep;
        }
        [BindProperty]
        public Student student{ get; set; }

        public void OnGet()
        {
            student = irep.GetFirst();
        }
    }

这是我的Main.cshtml:

@page
@model APWeb.Pages.MainModel

<h2>Main</h2>
<partial name="_test2" model="Model.student" />

这是我的部分视图:_test2:

@page
@*
    For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860
*@

@model Student
@{ 
<h1 >@Model.Name</h1>}

我在局部视图中的模型为空,并且出现此错误:

NullReferenceException: Object reference not set to an instance of an object.
APWeb.Pages.Shared.Pages_Shared__test2.get_Model()

任何帮助将不胜感激。

asp.net-core partial-views razor-pages asp.net-core-2.1 asp.net-mvc-partialview
1个回答
0
投票

部分视图必须是视图页面,而不是剃刀页面。这是一个演示工作:主页:

public class MainModel : PageModel
    {
        [BindProperty]
        public Student1 student { get; set; }
        public void OnGet()
        {
            student = new Student1 { Name = "Moddy" };
        }
    }

Main.cshtml:

@page
@model ModelValidation_MVC_.Pages.MainModel
@{
    ViewData["Title"] = "Main";
}

<h1>Main</h1>
<partial name="_test2" model="Model.student" />

_ test2.cshtml:

@model ModelValidation_MVC_.Models.Student1

<h1>@Model.Name</h1>

Student1.class:

public class Student1
    {
        public string Name { get; set; }
    }

结果:enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.