2

So, I have this variable that I push into the controller via POST from a form in my view.

I then push the variable into viewdata so it's available to the next view which is fine. But that view has no need of a form so I'm unable to push that same variable into the next controller. In short, it's cumbersome to push pieces of information back and forth from controller to view and reverse, so I'm looking for a way to keep a global variable alive inside a controller so that it's accessible by all action results... The general breakdown of my program is this...

-User types a "name"

-I send "name" to controller.
-I push 'name' into viewstate (query entity framework to get a list of stuff 'name'
   has access to) and return that list into the view.
-In that view I can access the 'name' since it was in view state.
-Clicking on a link inside the page takes me to another controller where I need 
   to get access to 'name' WITHOUT passing view Routing or POST.

Obviously the easiest way would be to declare 'name' globally and then it's always available but for the life of me I can't figure out how.

3 Answers 3

8

Have you considered storing it in the Session?

This will allow you to easily access it, either from your controller or views, and avoids the need for global variables.

Storing:

[HttpPost] 
public ActionResult YourPostMethod(string name)
{
    Session["Name"] = "yourName";
}

Access: *

Make Sure to check that it exists prior to grabbing it:

var whatsMyName = (Session["Name"] != null) ? Session["Name"] : "";

Scalability Consideration

It's worth mentioning that MVC applications are designed to mimic the web and are stateless. Introducing Session variables changes this, so be aware that it can introduce issues regarding scalability, etc.

Each user that stores data within the Session will take up resources at the server level. Depending on the number of users and what you are storing within the Session, you could potentially run out of memory if those values become too large.

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

Comments

0

Why not use the session object, which is an associative array which lives while the client is connected?

Comments

0
$_SESSION['name'] = "zzzz"; // store session data
name = $_SESSION['name']; //retrieve data

You can use this for each user till their session is active.. hope this helps

1 Comment

Not a PHP question.

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.