0

Is it possible to work with a global variable that need to receive the data from a query string in MVC controller?

public string Layout = Request.QueryString["Layout"];

At the moment I am working with a Session variable - but i want to use a global variable so it will be available all over my controller functions. Thanks

4
  • yes you can do it. But what i suggest you is. Declare a variable in controller and assign it in controller constructor. Commented Dec 29, 2016 at 8:19
  • what are you trying to achieve? Commented Dec 29, 2016 at 8:22
  • I have a certain page that i wish to redirect from with a parameter in the query string, this parameter should be received by the Controller and should be available through out the entire controller and functions. Commented Dec 29, 2016 at 9:03
  • You may use TempData but don't forget to use the Keep() method to keep the data upon navigating from one controller to other. Commented Dec 29, 2016 at 12:24

1 Answer 1

0

If you want global variable that will be global for all requests in your App you can use HttpContext.Application.

You can use it like this in any Controller method:

// set variable
HttpContext.Application["MyGlobalVar"] = 777; 
//get your variable
var myGlobalVar = Convert.ToInt32(HttpContext.Application["MyGlobalVar"]) 

Note that it stored like object so you should convert your variable when you get it.

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

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.