[英]Cannot pass data from Controller to View using ViewBag
I set ViewBag in my Controller constructor and use it in _Layout.cshtml.我在 Controller 构造函数中设置 ViewBag 并在 _Layout.cshtml 中使用它。 This is what I have done many times in ASP.NET MVC (.NET Framework).
这是我在 ASP.NET MVC(.NET Framework)中多次做过的事情。 The same code is not working in my new .NET6 ASP.NET Core application.
相同的代码在我的新 .NET6 ASP.NET 核心应用程序中不起作用。
public HomeController(ILoggerFactory logger)
{
CurrentUser = GetCurrentUser();
ViewBag.CurrentUser = CurrentUser;
}
In _Layout.cshtml I have below code在 _Layout.cshtml 我有以下代码
</head>
@{
AppUser _curUser = ViewBag.CurrentUser;
// _curUser is null here!!
}
<body>
I also tried using ViewData
but the same problem.我也尝试使用
ViewData
但同样的问题。 I have done this many times in all my MVC web applications and I'm wondering why it's not working now.我在所有 MVC web 应用程序中都这样做了很多次,我想知道为什么它现在不起作用。
The ViewData
and ViewBag
refer to the same underlying ViewData
collection. ViewData
和ViewBag
引用相同的底层ViewData
集合。 Actually life of the ViewData
or the ViewBag
lies only during the current request.实际上
ViewData
或ViewBag
的生命只存在于当前请求期间。
I suppose that in your case result might be depending on the dependency injection used in your application.我想在您的情况下,结果可能取决于您的应用程序中使用的依赖注入。
For additional information see Pass data to views有关其他信息,请参阅将数据传递给视图
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.