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

Vetri picture Vetri · Feb 12, 2014 · Viewed 39.1k times · Source

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")



        }

}

Answer

Rohan picture Rohan · Feb 12, 2014

I think you could access the session variable directly using

@HttpContext.Current.Session["Username"].ToString();