Tuesday, April 22, 2014

Auto PostBack to refresh content

Set a timer to auto postback page using JavaScript


//Register Auto PostBack
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "PostBackFunction", GetPostBackFunction(), true);

//Function to detail script
private string GetPostBackFunction()
{ StringBuilder build = new StringBuilder();

build.AppendLine(string.Format("window.setTimeout(\"AutoPostBack()\", {0});", (1000 * secondsForAutoPostBack).ToString()));
build.AppendLine("function AutoPostBack()");
build.AppendLine("{javascript:__doPostBack('AspControl','');}");

return build.ToString();
}
Note: "AspControl" in the javascript postback is the ID of an asp.net control on the page this script is being registered on.  If none exists, add one:

<asp:LinkButton runat="server" ID="AutoPostBackLb" Text=""></asp:LinkButton>

No comments: