0

I am trying to access a session variable inside a MVC razor view, the session variable is of type User which has a property UserID, the code is like the following:

<h3>@((User)Session["LoggedOnUser"]).UserID</h3>

It only prints the fully qualified type of the property instead of its value. I also tried the following:

@{User loginUser = (User)Session["LoggedOnUser"];}
<h3>@loginUser.UserID</h3>

It works this time. Can anyone tell me what's the difference of these two and why the first one does not work?

Thanks.

1
  • Could you share how you applied session on the specific User domain? do i simply add session declaration in the User controller and that is that? Commented Oct 6, 2017 at 2:37

1 Answer 1

1

This is because of where you placed your close bracket for the Response.Write (@) code block. You are calling Response.Write on the User object and not the UserID property. I believe calling Response.Write on the user ojbect will just use the ToString() method and return the fully qualified type name.

The following would have worked:

@((User)Session["LoggedOnUser"].UserID)

Notice the close bracket is after the property, not after the return value from the session dictionary.

Sign up to request clarification or add additional context in comments.

1 Comment

That makes sense. I changed it as following and it works: @(((User)Session["LoggedOnUser"]).UserID)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.