fyodorfranz
fyodorfranz

Reputation: 486

Updated variable doesn't maintain it's updated value

I have a dictionary named topics which I initialize and then assign variables to within Page_Load like so.

public partial class index : System.Web.UI.Page
{
    public static Dictionary<string, bool> topics { get; set; }

    protected void Page_Load(object sender, EventArgs e)
    {
        topics = new Dictionary<string, bool>
        {
            {"Books", false},
            {"Bikes", false},
            {"Binders", false},
        };
    }

 //...

}

Then on a button click, I try to invert one of the dictionary items, and display its value in an alert.

 protected void Button4_Click(object sender, EventArgs e)
    {
        topics["Books"] = !topics["Books"];

        ScriptManager.RegisterClientScriptBlock(this, typeof(Page),    
        "alert", "alert('" + topics["Books"] + "');" + slider, true);
    {

The alert, "true," tells me that value has changed within the function, however, when I click again, I get "true" again, which tells me that the the update isn't maintained after the function ends.

How can I make this update stick?

Upvotes: 1

Views: 126

Answers (2)

Cizaphil
Cizaphil

Reputation: 520

From what you have explained and what I have seen, you are trying to persist data, across page request without using any persistence mechanism, so what happens is that on each page request, the 'topics dictionary' is re-initialized and that's why you lose your value. Though am not sure of how it is done in asp.net but what you should do is to either persist the dictionary using cache, database, or if am right using viewstate in the case of asp.net so that the value will survive multiple requests.

Upvotes: 1

Tony L.
Tony L.

Reputation: 19506

It looks like you re-initializing the Topics Dictionary on each pageload. If you put an !IsPostBack around the code that initializes it, it won't re-initialize each time. However, I can't be sure that's the best way to handle this without knowing more about what you are trying to accomplish. Perhaps it would be better to check if topics is empty when deciding whether or not to initialize it like so:

if ((topics == null)) {
    topics = new Dictionary<string, bool>
    {
        {"Books", false},
        {"Bikes", false},
        {"Binders", false},
    };
}

Upvotes: 1

Related Questions