Why does a boolean always return to false;

I have a boolean variable declared at the top of the class, and when the switch is selected on the page, the variable gets true, but when the page reloads, the variable gets reset back to false. One way I dealt with this is to use the static keyword, but I'm not sure if this is the best way to deal with this. Here is a class in which I tried to do something in the Page_Load event, but it still resets the variables to false.

public class SendEmail
{
    bool AllSelected;

protected void Page_Load(object sender, EventArgs e)
{
    if(!Page.IsPostBack)
    {
        AllSelected = false;
    }
}

protected void rbAll_SelectedIndexChanged(object sender, EventArgs e)
{
    if(rbAll.SelectedValue == "All")
       AllSelected = true;
}

public Send()
{
   if(AllSelected)
   {
       //Send Email. Never runs because AllSelected is always false;
   }
}

}   
+3
source share
7 answers

, , . viewstate, , :

bool AllSelected
{
    get
    {
        object o = ViewState["AllSelected"];
        if(o == null) return false;
        return (bool)o;
    }
    set
    {
        ViewState["AllSelected"] = value;
    }
}

ViewState " ".

+16

, asp.net , . , AllSelected false.

, , - Send() SelectedIndexChanged.

+2

. ViewState ViewState, .

, , Send.

+2

boolean - , ( bools).

+1

, . .

+1

- ... ,

rbAll.SelectedValue == "All" 

?

No storage ... does not populate ViewState or Session with data that is not needed ...

+1
source

I really don't know if this will be useful in asp.net, but I am creating a new bool in the properties. settings so that it remembers bool whenever I close or restart the application. But I think this is more for winforms.

0
source

Source: https://habr.com/ru/post/1702783/


All Articles