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();
Author by
Vetri
Updated on February 12, 2020Comments
-
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 about 10 yearsIts 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 about 10 yearstry this
@Html.ActionLink(@HttpContext.Current.Session["Username"].ToString(), "NameOfHandlingFunction");
-
user629283 about 8 yearsHow would you do that if the session is an object?