【问题标题】:model in partial view is null - asp.net core razor pages部分视图中的模型为空 - asp.net core razor pages
【发布时间】:2020-10-04 05:28:00
【问题描述】:

我正在使用 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】:

    我通过从部分视图中删除“@page”解决了我的问题。

    【讨论】:

    • 谢谢。你救了我的一天!这正是所需要的。 :)
    【解决方案2】:

    部分视图需要是视图页面而不是剃须刀页面。 这是一个演示: 主页:

    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>
    

    学生1.班级:

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

    结果:

    【讨论】:

    • 你的代码和我的一样,唯一的不同是关键:从局部视图中删除@page。无论如何,谢谢,
    猜你喜欢
    • 2019-07-25
    • 1970-01-01
    • 2018-04-05
    • 1970-01-01
    • 2020-10-27
    • 2018-10-29
    • 2021-04-10
    • 2020-06-26
    • 2020-05-08
    相关资源
    最近更新 更多