【问题标题】:code behind ASPX page is not executing js codeASPX 页面后面的代码没有执行 js 代码
【发布时间】:2018-12-07 03:19:25
【问题描述】:

我有一个带有 VB.NET 的 .aspx 页面,在这个页面中我只运行一个查询并创建和导出一个 Excel 文件。在代码的某些部分中,我尝试执行任何 JS 代码(alert、console.log 等),并且我尝试了不同的方式,例如:

  • Response.Write
  • ScriptManager.RegisterStartupScript
  • lblJavaScript.Text = "script type='text/javascript'>execute();/script>".

但以上选项均无效。

我的代码是这样的:

Public Sub btnSubmit_Click(sender As Object, e As EventArgs) Handles btnSubmit.Click
    Try
        CreateExcel()
    Catch ex as Exception
    Finally
        '' Kill other process
    End Try
End Sub

Public Sub CreateExcel()
    '' Do a lot of things for example run a query, open a write on an Excel file, etc...

    '' This function has a lot of importance I will explain why below
    DownloadReport(oExcel, "MyExcelFile.xlsx", Response)

    Response.Write("<script type='text/javascript'>console.log('Hello 0');</script>")
End Sub

重要提示:逐步调试我的代码我发现如果我删除或注释 DownloadReport 行,我的 JS 代码就会被执行,所以我几乎可以肯定问题出在这个函数上。

下载报告代码:

Public Sub DownloadReport(ByVal app As Microsoft.Office.Interop.Excel.Application, ByVal Filename As String, ByRef Response As HttpResponse)
    Response.Write("<script type='text/javascript'>console.log('Hello 1');</script>")
    Dim bytesInStream As Byte() = GetActiveWorkbook(app)
    '' I know that Response.Clear deletes the above Response.Write
    Response.Clear()

    '' If I comment the above lines the Js on Response.Write also works
    Response.AddHeader("Content-Disposition", "attachment; filename=" & Filename)
    Response.AddHeader("Content-Length", (bytesInStream.Length))
    Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
    Response.BinaryWrite(bytesInStream)
    HttpContext.Current.ApplicationInstance.CompleteRequest()
    Response.Write("<script type='text/javascript'>console.log('Hello 2');</script>")
End Sub

如果我在控制台上评论 DownloadReport,我会看到 Hello 0。

如果我在控制台上对 DownloadReport 函数的 5 行进行注释,我将按该顺序看到 Hello 2 和 Hello 0。

如果我不评论任何内容,我将不会在控制台上看到任何内容,也不会出现 js 错误消息。

我的代码有什么问题,我该如何解决?

【问题讨论】:

    标签: javascript asp.net vb.net


    【解决方案1】:

    标头"Content-Disposition:attachment; filename=filename" 告诉您的浏览器将响应保存为文件,而不是将其呈现为HTML。 在文本编辑器中打开下载的文件,你会在末尾看到script标签。

    【讨论】:

    • 好的,我明白这一点,所以有一个替代方法可以删除该行,或者我应该怎么做?重要的是我的 js 代码可以工作,但我不能使用 ajax。
    猜你喜欢
    • 1970-01-01
    • 2021-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-18
    • 1970-01-01
    • 2017-10-16
    • 1970-01-01
    相关资源
    最近更新 更多