如何将数据从布局传递到剃须刀页面

发布于 2025-02-03 20:47:33 字数 617 浏览 2 评论 0 原文

我在_layout.cshtml的开头使用以下代码。

@{
    bool isAuthenticated = false;
    var userPingDTO = new UserPingDTO();
    try
    {
        userPingDTO = await userData.GetUserPing();
        isAuthenticated = true;

    }
    catch (Exception e)
    {
        Console.WriteLine(e);
        isAuthenticated = false;
    }
}

它用于检查用户是否已登录。我想做的是将所有剃须刀页面上的等法变量提供。因此,例如index.cshtml页面可以访问iSauthenticatiencatienated变量。

编辑澄清: 我试图使用ViewBag等,但它们似乎不起作用。我上面发送的代码存在于_layout文件中,而不是页面文件中。所以我想要的是布局 - >页面。如果我放断点,@page代码似乎先击中。之后,布局代码被击中。因此,ViewBag适用于Page-≫布局,但对于布局 - >页面而不做。

I am using the below code at the beginning of my _Layout.cshtml.

@{
    bool isAuthenticated = false;
    var userPingDTO = new UserPingDTO();
    try
    {
        userPingDTO = await userData.GetUserPing();
        isAuthenticated = true;

    }
    catch (Exception e)
    {
        Console.WriteLine(e);
        isAuthenticated = false;
    }
}

It is used to check if a user is logged in. What i want to do is make available the isAuthenticated variable to all Razor Pages. So for example an Index.cshtml page can access the isAuthenticated variable.

Edit for clarification:
I have tried to use ViewBag etc but they don't seem to work. The code i sent above exists inside the _Layout file, not in the page file. So what i want is Layout->Page. If i put breakpoints the @page code seems to be hit first. After that the Layout code is hit. So ViewBag works for Page->Layout but not for Layout->Page.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

烟─花易冷 2025-02-10 20:47:33

我以错误的方式处理问题。必须在每个页面开始时执行的代码必须将其放置在_viewStart文件中,而不是_layout文件中。因此,执行顺序为_viewStart-> page-> _layout。在_viewStart文件中使用特定值的ViewData填充视图之后,所有内容都可以正常工作。
从文档中:

需要在每个视图或页面之前运行的代码
_viewstart.cshtml文件。

I was approaching the problem the wrong way. Code that has to be executed on the start of every page load has to be placed in a _ViewStart file instead of the _Layout file. So the order of execution is _Viewstart->Page->_Layout. After populating the ViewData with the specific value in the _ViewStart file everything worked correctly.
From the documentation: https://learn.microsoft.com/en-us/aspnet/core/mvc/views/layout?view=aspnetcore-6.0

Code that needs to run before each view or page should be placed in
the _ViewStart.cshtml file.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文