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. :/
The Session value will be displayed using Razor Syntax in ASP.Net MVC. In the below example, a string value is set in the Session object in Controller and it is then displayed in View using Razor Syntax.
You can add support for Pages to any ASP.NET Core MVC app by simply adding a Pages folder and adding Razor Pages files to this folder. Razor Pages use the folder structure as a convention for routing requests.
By default, Asp.Net MVC support session state. Session is used to store data values across requests. Whether you store some data values with in the session or not Asp.Net MVC must manage the session state for all the controllers in your application that is time consuming.
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:
@if (Session["UserId"] != null && Session["UserId"] == 10 ) {
Html.Partial("LoggedMenu");
}
Apart from that: for identity management better use the out of the box membership system
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With