I set ViewBag in my Controller constructor and use it in _Layout.cshtml. This is what I have done many times in ASP.NET MVC (.NET Framework). The same code is not working in my new .NET6 ASP.NET Core application.
public HomeController(ILoggerFactory logger)
{
CurrentUser = GetCurrentUser();
ViewBag.CurrentUser = CurrentUser;
}
In _Layout.cshtml I have below code
</head>
@{
AppUser _curUser = ViewBag.CurrentUser;
// _curUser is null here!!
}
<body>
I also tried using ViewData
but the same problem. I have done this many times in all my MVC web applications and I'm wondering why it's not working now.
The ViewData
and ViewBag
refer to the same underlying ViewData
collection. Actually life of the ViewData
or the ViewBag
lies only during the current request.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.