开发者

insert javascript only on page postback

I'm sure this is fairly straightforward but i'm having trouble getting it to work. I want to add a javascript function to my page, but only when the page postsback.

So I have a button that calls some server-side code, and when it is finished and the page is re-loading I want the javascript function to be called.

Thinking about this i guess I could just add a hidden variable and set it when the button is clicked, but i think i'd rather just insert the javascript onto the page when it is loading back.

Is this possible, or even a good way to do it?

Thanks, Neil

Edit: Okay this is my OnClick method in the C# code.

protected void Save(object sender, EventArgs开发者_如何学运维 e)
{
    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", "<script type=\"text/javascript\">alert('hello world');</script>"); 
    EnforcementMatch(false);
    EnforcementMatch(true);
    ApplicationNotMatch();
    ApplicationMatch();
    Response.Redirect(Request.Url.ToString());
}

Another Edit: Just realised that the response.redirect at the bottom reloads my page cancelling out the code I put in, duh!


You can use ClientScriptManager.RegisterClientScriptBlock

http://msdn.microsoft.com/en-us/library/btf44dc9.aspx

If you place it on the button click event, you don't have to worry if it's a postback or not.


You know about the IsPostBack function, right?

IsPostBack (MSDN)

if (IsPostBack)
{
    ClientScript.RegisterClientScriptBlock()
}


This script will be fired with every single postback from updatepanel

<script type="text/javascript"> 
    var prm = Sys.WebForms.PageRequestManager.getInstance(); 
    prm.add_endRequest(function ()    {
        alert('hello world');
    });
</script>


Place it in a separate script block, only to be rendered on postback.

<script type="text/javascript" runat="server" visible="<%#this.IsPostBack %>">
    TheCode();
</script>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜