登录后,ASP.NET MVC在站点顶部显示用户名

时间:2014-02-27 17:58:07

标签: asp.net-mvc asp.net-mvc-4

我想在屏幕顶部保留用户名。我有多个视图和控制器。我想保留相同的值,即使我导航到不同的页面。

我用过

 @Html.DevExpress().Label(settings =>
 {
    settings.Text = ViewBag.Name;

  }).GetHtml()

我在shared folder - _mainLayout添加了此标签(因此该标签应该在所有页面中都可用)

我还尝试过会话变量,ViewData和Tempdata。但价值只保留在一个视图中。当我导航到另一个视图时,它不会渲染。

如何实现这一目标?

2 个答案:

答案 0 :(得分:2)

如果您需要当前用户的名字,最好这样做:

 @Html.DevExpress().Label(settings =>
 {
    settings.Text = this.User.Identity.Name;

 }).GetHtml()

ViewBag,ViewData和Tempdata仅在页面上有效,您已经从设置它们的控制器移动/重定向。

修改

//set cookie
var cookie = new HttpCookie("username", "ElectricRouge");
Response.Cookies.Add(cookie);

//Get cookie
var val = Request.Cookies["username"].Value;

答案 1 :(得分:0)

此方法使用Action Filter Attribute类来处理控制器上的操作执行。首先,您需要创建一个新的Action Filter类,将其调用为您想要的任何类,但要使其继承自ActionFilterAttribute类。然后,您应该使用ActionExecutedContext参数添加覆盖的OnActionExecuted方法:

public class ExampleActonFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        BaseViewModel model = filtercontext.Controller.ViewData.Model;

        if (filterContext.Controller.ControllerContext.HttpContext.Session["UserName"] != null)
        {
            model.UserName = filterContext.Controller.ControllerContext.HttpContext.Session["UserName"];
        }
    }
}

接下来,您的布局页面采用带有公共字符串参数的ViewModel,将用户名作为字符串:

 public class BaseViewModel()
{
    public string UserName {get;set;}
}

然后在你的布局页面上有一个简单的检查(你希望它被绘制的地方)以确保该值不为空,如果不是,则绘制它如下:

if (string.IsNullOrWhiteSpace(@Model.UserName))
{
    <span>@Model.UserName</span>
}

现在,在您要显示用户名的所有视图中,只需将该页面的ViewModel继承自BaseViewModel类,并在需要显示时将用户名设置为会话变量。

有关会话变量的更多信息,请查看此SO帖子:here

我希望这有帮助!