1

I want to retain the user name on top of the screen. I have multiple views and controllers. I want to retain the same value even though when I navigate to different pages.

I have used

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

  }).GetHtml()

I have added this label in shared folder - _mainLayout (So that label should be available in all the pages)

I also tried with session varibles, ViewData and Tempdata. But the value is retaining only in one view. When I navigate to another view it is not rendering.

How can this be accomplished?

ElectricRouge
  • 1,239
  • 3
  • 22
  • 33

2 Answers2

2

If you need the current user's name, you are better to get it this way:

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

 }).GetHtml()

ViewBag, ViewData and Tempdata are only valid on the page, there you've been moved/redirected from the controller, where you set them.

EDIT:

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

//Get cookie
var val = Request.Cookies["username"].Value;
VladL
  • 12,769
  • 10
  • 63
  • 83
0

This method makes use of an Action Filter Attribute class to handle action execution on controllers. Firstly you need to create a new Action Filter class, calling it anything you want, but make it inherit from the ActionFilterAttribute class. You should then add the overrided OnActionExecuted method with the ActionExecutedContext argument:

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"];
        }
    }
}

Next, you have your layout page take a ViewModel with a public string parameter taking the username as a string:

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

Then on your layout page have a simple check (where you would like it to be drawn) to make sure that value is not null and if it isn't, to draw it like so:

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

Now in all of your views where you want to show the user name, simply have your ViewModel for that page inherit from your BaseViewModel class and set the username to the session variable when you want it to be shown.

Have a look at this SO post for more information about session variables: here

I hope this helps!

Community
  • 1
  • 1
Aegis
  • 190
  • 1
  • 11