0

I'm trying to implement a shared property in my C# controller where I've defined it like this:

public string guid;
    public string _gu_id
    {
        get { return guid; }
        set { guid = value; }
    }

public ActionResult ActionFirst()
{
 _gu_id = something...;
}

public ActionResult ActionSecond()
{
// checking now if the _gu_id is !=null
if(_gu_id!=null)
// do something here
}

Like this the property gets set in the first action but its value is not available in 2nd one...

I can declare it as static but that is not a solution as static variable should be avoided in web.. ?

Edit: To explain the problem in more details:

When the proprety _gu_id is set in first ActionFirst method, I need to be able to fetch its value in ActionSecond method, without using static variables...

User987
  • 3,663
  • 15
  • 54
  • 115
  • 1
    XY problem. You have a problem, for which you think the solution is "create a member variable in my controller". Explain what problem you're trying to solve by that, because controllers are created per request. You probably need to store something in a session, token, header or elsewhere. – CodeCaster Dec 20 '16 at 14:42
  • @CodeCaster The problem is as following: the variable GUID needs to be available in 2nd method when set in first method...I mentioned I could use static variable for this but I'm avoiding to use them since I've had very unpleasant experience with them... – User987 Dec 20 '16 at 14:43
  • @CodeCaster So upon setting the _gu_id variable in first method, when 2nd method is called, I need to have the _gu_id value in second method which was set in first method... – User987 Dec 20 '16 at 14:44
  • 2
    _"the variable GUID needs to be available in 2nd method"_ - then stick it in a session, in a database, or pass it to the user for them to return upon the second request. – CodeCaster Dec 20 '16 at 14:47
  • @CodeCaster Alrighty good point, session seems like the best solution, thanks ! :) – User987 Dec 20 '16 at 14:48

2 Answers2

4

Whenever you are redirecting to new action method of a new controller this a new request and you can't retain value from one request to another like the way you are looking for.

Rather use Session variable like this.

Session["guid"] = "YourValue";
Anadi
  • 744
  • 9
  • 24
2

If you are avoiding using persistent session variables (usually a good idea), MVC also offers TempData for hanging onto data between redirects.

Community
  • 1
  • 1
John Wu
  • 50,556
  • 8
  • 44
  • 80