1

So when you make websites using Java you have something called a Session in which you can store any information you want basically for as long as that browser session is going on.

I'm fairly new with using ASP.NET MVC 3 and being able to pass around the right data at the right time is something that leaves me tied up quite often. For the most part I understand passing variables from views to controllers and back to other views.

But I was wondering if there's a way to make something that allowed to to let's say, grab a user's address from any view? I know there is User.Identity.Name built in and this is very handy for checking that a user is on their own page, etc. But is there any way to have a User object with custom information that is accessible anywhere?

I'm currently working on having a reputation system on my website (much like this website) where different amounts of reputation allow you to do different things. So in a lot of views I need to say "Hey, if the user has this reputation, let them see this feature." But this is extremely tedious if I have to pass in a user into every single view.

Any ideas?

2 Answers 2

1

I think you're looking for HttpContext.Session.

If you want more info on session and ASP.NET MVC, take a look at this article to get a better understanding on when session is available during a request.

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

Comments

1

You can keep your custom class object is Session. Session will be available across requests.

Assuming you have a class like this

public class LoggedInUser
{
  public string DisplayName { set;get;}
  //Other relevant properties. relevant only not everything !
}

and you can store it in session like this

LoggedInUser objLoggedInUser=new LoggedInUser();
objLoggedInUser.DisplayName="Johnson";
Session["LoggedUser"]=objLoggedInUser;

Now wherever you want this, you can read it from session like this

LoggedInUser objLoggedInUser;
if(LoggedInUser objLoggedInUser=!=null)
{
  objLoggedInUser=(LoggedInUser)Session["LoggedUser"];
  // Now you can access objLoggedInUser.DisplayName
}

I would wrap this functionality into a function and call that function to get the data wherever i want.

Comments

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.