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

1

5

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



        }

}

Matthiew answered 12/2, 2014 at 9:6 Comment(0)
T
17

I think you could access the session variable directly using

@HttpContext.Current.Session["Username"].ToString();
Tudor answered 12/2, 2014 at 9:15 Comment(3)
Its working,Thank you very much,,,But the session user name is displaying like as Label,,,How to make it as hyper link,,,pls helpMatthiew
try this @Html.ActionLink(@HttpContext.Current.Session["Username"].ToString(), "NameOfHandlingFunction");Tudor
How would you do that if the session is an object?Marek

© 2022 - 2024 — McMap. All rights reserved.