I wrote many websites with PHP. Now, I have to create website with ASP MVC 4 (c#) and I am stuck with Sessions.
I.E. the user should go to login page, enter his/her login and password. If they are correct, in controller, I set the session with UserId, like this:
Session["UserId"] = 10
This UserId value is used for showing PartialViews (login form or (after login) some application menus). How can I get this UserId inside Razor view ?
After this in View:
if (Session.UserId == 10) { @Html.Partial("LoggedMenu") }
i've got exception with StackOverflow. :/
you're doing it wrong...
Session[<item name>]
returns a string, you should compare with a string as well, or cast it, so, either (int)Session["UserId"] == 10
or Session["UserId"] = "10"
.
you also are invoking a property that does not exist Session.UserId
will not exist as Session
is like an NameValueCollection, you call it by request it's item name.
at the end, you should write
@if (Session["UserId"] == "10") {
Html.Partial("LoggedMenu");
}
You say your are learning, so I would like to point out 2 quick things: