在Response.End()之后从代码中调用JavaScript函数

时间:2014-12-26 11:35:07

标签: asp.net c#-4.0 httpresponse

在我的.aspx页面中,我有一个div,我需要在下载附件后使用JavaScript隐藏它。我使用下面的代码来完成它。但是,由于Response即将进入场景,HideDiv()不会被解雇。

我甚至尝试将div设为服务器控件并将可见性设置为false。我还尝试将ClientScript部分放在Response.End();之后和finally块内。

    try{

    ClientScript.RegisterStartupScript(this.GetType(), "Hide", "HideDiv()", true);
    Response.ContentType = "application/vnd.ms-excel";
    Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + "");
    Response.Write(tw.ToString());
    Response.End();
}
catch (System.Threading.ThreadAbortException)
        {

        }
        catch (Exception ex)
        {
            //log error
        }
        finally
        {

        }

有任何想法让JavaScript工作吗?

3 个答案:

答案 0 :(得分:3)

创建.aspx Generic Handler下载文件然后你可以这样称呼它

ClientScript.RegisterStartupScript(this.GetType(), "Hide", "HideDiv()", true);
Response.Redirect("MyHandler.ashx")

OR

js函数隐藏div和Redirect

function HideDivNRedirect()
{
  //hide div
window.location.href='myhandler.ashx';
}

ClientScript.RegisterStartupScript(this.GetType(), "Hide", "HideDivNRedirect();", true);

答案 1 :(得分:1)

您可以从后面的代码中调用该函数:

Form.aspx.cs

如果您想拨打button click

protected void Button_Click(object sender, EventArgs e)
{
 Page.ClientScript.RegisterStartupScript(this.GetType(), "Hide", "HideDiv();", true);
}

答案 2 :(得分:1)

在代码后面调用javascript函数在Response.End();之后无法使用但是可以使用beforeunload,它会在response.End();之后触发

$(window).bind('beforeunload', function() {
    // here your function
});