从 Dotnet Core 2.2 升级到 Dotnet 5部分不再获得查看数据

问题描述

原始问题

我正在努力将 web 应用程序从 dotnet core 2.2 更新到 dotnet 5。大多数事情都运行良好,但我被困在部分视图上。

该网站使用了大量的 Ajax 请求,并且大多数返回带有一些 html 的小部分视图。 partial中的所有变量信息都是通过viewdata设置的。

更新到 dotnet 5 后,viewdata 作为空进入部分。

例如,我要返回部分“_mailbox”。在控制器中,您可以看到我在 viewdata 中有东西:

enter image description here

但是当我进入部分时,您会看到它是空白的! 2.2中通过了。

enter image description here

基本功能-

public ActionResult OnGetGetMailbox(int id)
{
  ViewData["Fullname"] = "Christopher"
  return Partial("_mailbox")
}

您知道哪里出了问题吗?我基本上只是按照 Microsoft 概述的步骤操作。

如何重现

所以我开始了一个全新的项目来测试并遇到同样的问题 -

enter image description here

enter image description here

添加一个新的 html 部分 _test.cshtml

enter image description here

index.cshtml.cs中添加一个新函数

enter image description here

然后在运行 web 应用程序时 https://localhost:44332/?Handler=test

我应该看到我的名字-

enter image description here

但它是空白的。在调试和单步执行时,我看到视图数据没有传递给视图。

其他信息

  • 它适用于 Dotnet Core 2.2.105。

  • 根据 docs 与 2.2 相同的语法应该在 5.1 中工作。但是,正如@Brando Zhang 指出的那样,您必须使用 dotnet 2.1 中过时的语法才能完成这项工作。

  • 如果您阅读了 dotnet 5 Partial 函数的文档,它声称自己是 Microsoft.AspNetCore.Mvc.RazorPages 命名空间的一部分,但是如果您尝试使用该命名空间,您会发现 Partial 确实如此不存在。 see docs

enter image description here

这是一个错误吗?

解决方法

据我所知,返回的 Partial 是 MVC 函数的结果,不是 razor 页面,如果你想使用 razor 页面的 Partial 结果,你应该自己构建。

更多细节,您可以参考以下代码:

    public IActionResult OnGetTest()
    {

        ViewData["Test"] = "test";
        var partialView = "_test";


        var partialViewResult = new PartialViewResult()
        {
            ViewName = partialView,ViewData = ViewData
        };
        return partialViewResult;
    }   

结果:

enter image description here

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...