kez kez - 1 year ago 127
C# Question

session's variables values retrieving in _LayoutPartial in mvc

I'm filling values to a session's like following to retrive those in _LayoutPartial view

if (userdata != null)
Session["userdata"] = new SampleViewModel { FirstName = userdata.UserFirstName, LastName = userdata.UserLastName };
FormsAuthentication.SetAuthCookie(loginmodel.UserName, false);
return RedirectToAction("Dashboard", "Home", new { username = loginmodel.UserName });

I want to retrive those values in _LayoutPartial View , So I tried somethin like following

<a class="sa">
(@Session["userdata"] as ProjectName.Models.SampleViewModel).FirstName
(@Session["userdata"] as ProjectName.Models.SampleViewModel).LastName

But this is not retrieving data properly . In this _LoginPartial I'm not Referencing any model also

Answer Source

You have your parenthesis in the wrong spot, and you need a double set - one for the casting (inner set) and one for the razor execution (outer set). It needs to be

@((Session["userdata"] as ProjectName.Models.SampleViewModel).Name)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download