views:

194

answers:

3

Dear guys

I tried to set a global variable with a livetime during one pagerequest.

In classic als i used this like this:


dim VariableName
VariableName = "test";

sub testsub()
    VariableName += VariableName + "new"
    response.write VariableName
end sub

response.write VariableName '-> test
testsub() '-> testnew

Now in asp.net i tryed to set the variable in my class like this:

public static class MyClass
{
    public static string GlobalVar = "test";

    public static string MyMethod()
    {
        GlobalVar += GlobalVar + "new";

        return GlobalVar;
    }
}

But now, the problem is, that this variable are like a application variable with a lifetime over all pagerequest.

Where can i define a varible with a lifetime during one request and availiable in all methods and other classes? Thank you for your help.

Best regards and a happy new year

+2  A: 

Try using ASP.NET Session and see if it fits yours needs.

Pedro
+4  A: 
HttpContext.Current.Items["ThisVariableHasRequestScope"] = "SomethingFancy";

Edit:

A simple example

AClass.cs :

public class AClass {
    public void Something() {
        // Set the value
        HttpContext.Current.Items["Test"] = "xxx";
    }
}

BClass.cs

public class BClass{
    public void SomethingElse() {
        // Get the value
        var test = HttpContext.Current.Items["Test"] as string;
    }
}
Diadistis
Thank you for your answer. I want to set this variable in MyClass and not in MyMethod(). Because I have to use this global variable in other files and classes, too. How I have to set this variable?
roniX
You're welcome. I've added a small example.
Diadistis
A: 

You can also to use Page.Context property as it will be available during all page lifecycle.

Rubens Farias