如何将数据从布局传递到剃须刀页面
我在_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-≫布局,但对于布局 - >页面而不做。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我以错误的方式处理问题。必须在每个页面开始时执行的代码必须将其放置在_viewStart文件中,而不是_layout文件中。因此,执行顺序为_viewStart-> page-> _layout。在_viewStart文件中使用特定值的ViewData填充视图之后,所有内容都可以正常工作。
从文档中:
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