Is there a way to force a postback in code?
I’m looking to force the raising of a postback from a method in the c# code behind my asp.net web application.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
You can try redirecting to same page.
Response.Redirect(Request.RawUrl);
Method 2
A postback is triggered after a form submission, so it’s related to a client action…
take a look here for an explanation:
ASP.NET – Is it possible to trigger a postback from server code?
and here for a solution:
http://forums.asp.net/t/928411.aspx/1
Method 3
Simpler:
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "DoPostBack", "__doPostBack(sender, e)", true);
Method 4
Here the solution from http://forums.asp.net/t/928411.aspx/1 as mentioned by mamoo – just in case the website goes offline. Worked well for me.
StringBuilder sbScript = new StringBuilder();
sbScript.Append("<script language='JavaScript' type='text/javascript'>n");
sbScript.Append("<!--n");
sbScript.Append(this.GetPostBackEventReference(this, "PBArg") + ";n");
sbScript.Append("// -->n");
sbScript.Append("</script>n");
this.RegisterStartupScript("AutoPostBackScript", sbScript.ToString());
Method 5
No, not from code behind. A postback is a request initiated from a page on the client back to itself on the server using the Http POST method. On the server side you can request a redirect but the will be Http GET request.
Method 6
You can use a data-bound control like the Repeater or ListView, re-bind it to a list of control properties as needed, and let it generate the controls dynamically.
As an alternative, you can use Response.Redirect(".") to re-load the same page.
Method 7
By using Server.Transfer(“YourCurrentPage.aspx”); we can easily acheive this and it is better than Response.Redirect(); coz Server.Transfer() will save you the round trip.
Method 8
You can manually call the method invoked by PostBack from the Page_Load event:
public void Page_Load(object sender, EventArgs e)
{
MyPostBackMethod(sender, e);
}
But if you mean if you can have the Page.IsPostBack property set to true without real post back, then the answer is no.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0