如何使用在控制器中定义的@ 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;
}
}
答案 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变量存储用户详细信息,并将其显示在共享视图中。