【问题标题】:model item passed into the ViewDataDictionary is of type 'MainModel', but this ViewDataDictionary instance requires a model item of type 'testModel'传递到 ViewDataDictionary 的模型项属于“MainModel”类型,但此 ViewDataDictionary 实例需要一个“testModel”类型的模型项
【发布时间】:2020-10-03 21:05:24
【问题描述】:

任何帮助将不胜感激! 我保持页面几乎是空的,以首先解决这个问题。 在布局页面中尝试了不同的方式来调用局部视图。 使用 asp.net 核心 2.1

我的部分视图肯定应该早于主页加载。现在它是空的,但它会包含一些要加载的数据。

这是我单次调用局部视图的布局:

<!DOCTYPE html>
<html>
<head>
</head>
<body>
    <div>
        <table>
            <tr>
                @await Html.PartialAsync("~/Pages/PartialPages/test.cshtml");
                @*<partial name="~/Pages/PartialPages/test.cshtml" />*@
            </tr>
        </table>
    </div>

    <div class="content">
    <div style="float: left; margin-left: 1%; width: 100%">
        @RenderBody()
    </div>
    </div>

    @RenderSection("Scripts", required: false)
</body>
</html>

我有空的“主”页面

public class MainModel : PageModel
    {
        public void OnGet()
        {

        }
    }

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

<h2>Main</h2>

这是我的部分视图页面:

public class testModel : PageModel
    {
        public void OnGet()
        {

        }
    }

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

我的主页使用布局页面。

【问题讨论】:

  • 登录后我重定向到“主”页面,但主页面使用布局和布局应该加载部分视图。所以请求是针对主页但部分视图应该在此之前加载,所以我认为这是冲突,但不知道如何解决。
  • 嗨@R_SH,如果我的回答对你有帮助,你能接受吗?参考:How to accept as answer。如果没有,请跟进让我知道。

标签: asp.net-core razor layout partial-views razor-pages


【解决方案1】:

您需要在初始化布局时将默认模型传递给您的 test.cshtml :

@await Html.PartialAsync("~/Pages/PartialPages/test.cshtml",new testModel());

【讨论】:

  • 我通过一些更改和传递模型解决了这个问题,但我认为你的也可以。无论如何,谢谢,
  • 如果我的回答对你有帮助,你能接受吗?参考:meta.stackexchange.com/questions/5234/…
猜你喜欢
  • 1970-01-01
  • 2020-10-20
  • 2022-01-27
  • 2018-12-25
  • 2022-06-27
  • 2021-12-24
  • 1970-01-01
  • 2021-09-21
相关资源
最近更新 更多