简体   繁体   中英

Server Transfer with preserveForm true in EventHandler refires that event Handler

Server Transfer with preserveForm true in EventHandler refires that event Handler and causes infinite loop. MY QUESTION: How can I indicate in the handler that the event has been handled.

PS: I know we can set the preserveForm to false, but I dont want to do that.

Sample Code:

protected void rbThemes_SelectedIndexChanged(object sender, EventArgs e)
{
    Server.Transfer(Request.FilePath, true); 
}

Great question that I'm facing right now. I don't know the answer either, I would imagine one would modify Request.Form data to remove the event, though I'm not sure how to do this cleanly.

As a workaround, I use a guard flag in Context.Items , which is preserved as well.

protected void rbThemes_SelectedIndexChanged(object sender, EventArgs e)
{
    if (IsSecondPass()) return;
    Server.Transfer(Request.FilePath, true); 
}

private bool IsSecondPass()
{
    const string key = "SECOND_PASS_GUARD";
    if (Context.Items[key] == null)
    {
        Context.Items[key] = new object();
        return false;
    }
    else
    {
        Context.Items.Remove(key);
        return true;
    }
}

I wouldn't recommend this, but it works. (Method name is also very poorly chosen as it side-effects.)

There's also a shorter way:

protected void rbThemes_SelectedIndexChanged(object sender, EventArgs e)
{
    if (PreviousPage != null) return;
    Server.Transfer(Request.FilePath, true); 
}

Beware that it doesn't have any undesired effects if you do other kinds of cross-page postings (though I don't know why or how you would cross-post a SelectedIndexChanged event from another page). Still not recommended.

Note: If you're coding a master page, you'll need to reference PreviousPage from the Page property on the master page class ( Page.PreviousPage ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM