如何从控制器到_layout页面获取@ ViewBag.UserName?

时间:2019-06-21 15:25:01

标签: asp.net-mvc

如何使用在控制器中定义的@ ViewBag.UserName显示在_layout页面中?这是来自控制器的代码:

                       var username = User.Identity.Name;

                using (var context = new PrincipalContext(ContextType.Domain, "domain.local"))
                {
                    var user = UserPrincipal.FindByIdentity(context, username);
                    DirectoryEntry directoryEntry = user.GetUnderlyingObject() as DirectoryEntry;
                    if (user != null)
                    {
                        ViewBag.UserName = user.Name;
                        ViewBag.EmailAddress = user.EmailAddress;
                    }
                }            

2 个答案:

答案 0 :(得分:1)

请注意,ViewBag的生命只在当前http请求期间持续。如果发生重定向,则ViewBag值将为空。

您应将用户信息保留在Session变量中。

if (user != null)
{
    Session["UserName"] = user.Name;
    Session["EmailAddress"] = user.EmailAddress;
}

在layout.cshtml

<p>@Session["UserName"]</p>

答案 1 :(得分:0)

Viewbag数据不会显示在_layout页面中。如果只是一个视图显示一次,则可以使用TempData,但是对于共享视图,将仅为第一个视图显示Tempdata。 因此,您应该使用Session变量存储用户详细信息,并将其显示在共享视图中。