简体   繁体   English

无法使用 ViewBag 将数据从 Controller 传递到 View

[英]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. ViewDataViewBag引用相同的底层ViewData集合。 Actually life of the ViewData or the ViewBag lies only during the current request.实际上ViewDataViewBag的生命只存在于当前请求期间。

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.

相关问题 将列表从 Controller 传递到使用 ViewBag 进行查看 - Pass List From Controller to View Using ViewBag 将viewbag从动作控制器传递到局部视图 - Pass viewbag to partial view from action controller 可以使用ViewBag将数据从视图传递到控制器或绑定到模型属性 - Can ViewBag be used to pass data from view to the controller or bind to model property 如何将ViewBag从控制器传递到View(Ajax Url) - How can I pass a ViewBag from controller to View(Ajax Url) 如何将foreach中的viewbag值从视图传递到表单提交的控制器 - How to pass viewbag values in a foreach from view to controller on form submit 如何同时传递 Notmapped 和 ViewBag 值以从 controller 查看? - How to pass both Notmapped And ViewBag value to view from controller? ViewBag.Something是否也可以将数据从视图传输到控制器? - Can a ViewBag.Something transport data from view to the controller as well? 如何在控制器中显示从Viewbag传递的数据以进行查看 - How do i display data passed from viewbag in controller to view 如何从控制器返回多个viewbag数据以进行查看? - How to return multiple viewbag data to view from controller? 使用 Ajax 将数据从视图传递到控制器 - Pass data from View to Controller using Ajax
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM