Home > Back-end >  Cannot pass data from Controller to View using ViewBag
Cannot pass data from Controller to View using ViewBag

Time:09-28

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.

CodePudding user response:

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

  • Related