【问题标题】:How to Use Razor Partial Tag Helper in a Layout如何在布局中使用 Razor 部分标签助手
【发布时间】:2021-03-08 17:23:30
【问题描述】:

在查看了旧的 Razor 应用程序后,我决定对其进行更新,但无法使部分标签助手工作,我升级到 Visual Studio (Community) 2019,因为我可以从那里找到所有信息,并制作了一个新的实际包含 Pages 文件夹的 ASP.NET Core 5.0 Razor 项目。

现在尝试使用使用部分的布局后,我收到以下错误:

InvalidOperationException:传递到 ViewDataDictionary 的模型项属于“WebApplication1.Pages.IndexModel”类型,但此 ViewDataDictionary 实例需要一个“WebApplication1.Pages.Shared.PartAModel”类型的模型项。

请告诉我我错过了什么简单的事情使这项工作奏效。

结果应该只有 3-5 个文件,所以我将在这里举例说明:

Index.cshtml:

@page
@model IndexModel
@{
    ViewData["Title"] = "Home page";
}

<div class="text-center">
    <p>
        This is the parent content.
    </p>
</div>

_Layout.cshtml:

<!DOCTYPE html>
<html lang="en">
<body>
   
    <div>
        @RenderBody()
    </div>

    <div>
        <partial name="PartA" />
    </div>
        
</body>
</html>

PartA.cshtml:

@page
@model WebApplication1.Pages.Shared.PartAModel
@{
}
This is where the child content goes.

索引.cshtml.cs:

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace WebApplication1.Pages
{
    public class IndexModel : PageModel
    {
        private readonly ILogger<IndexModel> _logger;

        public IndexModel(ILogger<IndexModel> logger)
        {
            _logger = logger;
        }

        public void OnGet()
        {

        }
    }
}

PartA.cshtml.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace WebApplication1.Pages.Shared
{
    public class PartAModel : PageModel
    {
        public void OnGet()
        {
        }
    }
}

【问题讨论】:

    标签: visual-studio-2019 razor-pages asp.net-core-5.0


    【解决方案1】:

    PartA.cshtml 页面与WebApplication1.Pages.Shared.PartAModel 强绑定。

    需要通过部分标签传递相同的模型:

    @{var part = new PartAModel;}
    <div>
       <partial name="PartA"  model="@part" />
    </div>
    

    另见How to pass a value into partial tag helper?

    【讨论】:

    • 谢谢!在我设法找到的任何“示例”中似乎都没有提到这件小事。
    猜你喜欢
    • 2019-11-07
    • 1970-01-01
    • 2021-07-06
    • 2017-03-22
    • 1970-01-01
    • 2020-05-06
    • 2011-05-30
    • 1970-01-01
    • 2017-03-22
    相关资源
    最近更新 更多