ringos staro
ringos staro

Reputation: 27

alter ViewState of aspx.cs from simple cs

If you had to communicate a value between two classes in asp.net, an aspx.cs and a simple .cs class, and the value has to be present throughout the user's session, how would you do it? the second class uses ViewState, I would like to alter the value of ViewState["VARIABLE1"] of class C2.aspx.cs from C1.cs, is that possible and how? C1 doesn't have a C1.aspx (it's not a user control but a simple class. Thank you for the advice.

Upvotes: 0

Views: 118

Answers (1)

Joel Coehoorn
Joel Coehoorn

Reputation: 415665

Here's the key:

the value has to be present throughout the user's session

Clearly, the main home for the variable should be in the session:

Session["VARIABLE1"]

However, I also see this:

I would like to alter the value of ViewState["VARIABLE1"] of class C2.aspx.cs from C1.cs

I suggest re-thinking C1.cs to use a more functional style. Design the classes there such that instead of something like this:

void C1Function()
{
    if (Session["VARIABLE1"] == "value") 
        Session["VARIABLE1"] = somevalue;
}

///...

class C2
{
    void Page_Load(object sender, EventArgs e)
    {
        C1TypeInstance.C1Function();
    }
}

you instead end up with code more like this:

string C1Function(sting VARIABLE1)
{
   if (VARIABLE1== "value")
      return somevalue;
   return VARIABLE1;
}

///...

class C2
{
    void Page_Load(object sender, EventArgs e)
    {
        Session["VARIABLE1"] = C1TypeInstance.C1Function(Session["VARIABLE1"]);
    }
}

or like this:

public class C1
{ 
    private string variable1;
    public C1(string VARIABLE1)
    {
        variable1 = VARIABLE1;
    }


    string C1Function()
    {
        if (variable1 == "value") 
            variable1 = somevalue;
        return variable1
    }
}

///...

class C2
{
    void Page_Load(object sender, EventArgs e)
    {
        var C1TypeInstance = new C1(Session["VARIABLE1"]);
        Session["VARIABLE1"] = C1TypeInstance.C1Function();
    }
}

or like this:

static string C1Function(sting VARIABLE1)
{
   if (VARIABLE1== "value")
      return somevalue;
   return VARIABLE1;
}

///...

class C2
{
    void Page_Load(object sender, EventArgs e)
    {
        Session["VARIABLE1"] = C1Type.C1Function(Session["VARIABLE1"]);
    }
}

And if all else fails, you can store an entire instance of your C1 type in the session, like this:

public class C1
{ 
    public string VARIABLE1 {get; set;}
}

///...

class C2
{
    void Page_Load(object sender, EventArgs e)
    {
        Session["VARIABLE1"] = Session["VARIABLE1"] ?? new C1();

        ((C1)Session["VARIABLE1"]).VARIABLE1 = "somevalue";
    }
}

Upvotes: 1

Related Questions