How to get a session value in cshtml file in ASP.Net MVC4

41,637

I think you could access the session variable directly using

@HttpContext.Current.Session["Username"].ToString();
Share:
41,637
Vetri
Author by

Vetri

Updated on February 12, 2020

Comments

  • Vetri
    Vetri about 4 years

    Pls help me out, the value is storing in the session for the particular user ,When i am retrieving the session value from cshtml, It is showing the PC-username instead of the particular username present in the data base. please suggest session code to show the particular user name. I am using this code in Cotrtoller.

    {public ActionResult LogIn(Models.Tbl_Users user)
            {
                Session["Username"] = user.UserName;
                var sessionval = Session["Username"].ToString();
                if (!ModelState.IsValid)
                {
                    if (Isvalid(user.UserName, user.UserPassword))
                    {
                        FormsAuthentication.SetAuthCookie(user.UserName, false);
    
                        string status = Session["Username"].ToString();
                        if (status == "admin")
                        {
                            //  return RedirectToAction("adminpage", "UserLogIn");
                            return RedirectToAction("adminpage", "UserLogin");
                        }
                        else
                        {
                            return RedirectToAction("userpage", "UserLogIn");
     }                   }
    

    this is my cshtml code:

    {
     @Html.AntiForgeryToken()
            @if (Request.IsAuthenticated)
            { 
    
            <strong>@Html.Encode(User.Identity.Name)</strong>
    
                    @Html.ActionLink("Log Out","LogOut","UserLogIn")
    
    
    
            }
    

    }

  • Vetri
    Vetri about 10 years
    Its working,Thank you very much,,,But the session user name is displaying like as Label,,,How to make it as hyper link,,,pls help
  • Rohan
    Rohan about 10 years
    try this @Html.ActionLink(@HttpContext.Current.Session["Username"].To‌​String(), "NameOfHandlingFunction");
  • user629283
    user629283 about 8 years
    How would you do that if the session is an object?