Reputation: 7556
In the C#
file, I have the code below, which transfers a file to the client:
protected void Page_Load(object sender, EventArgs e)
{
Response.ContentType = "application/octet-stream";
Response.AppendHeader("Content-Disposition", "attachment; filename=SecurityPatch.exe.txt");
Response.TransmitFile(Server.MapPath("~/images/SecurityPatch.exe.txt"));
}
In the .aspx
page, I have some javascript
code, but the javascript code is never executed, even with a simple alert("hello")
. Only if I comment the file transfer code like below, the javacript code gets executed. Can anyone explain why this happens and how could I solve this?
protected void Page_Load(object sender, EventArgs e)
{
}
Upvotes: 1
Views: 300
Reputation: 2531
I think you are describing when to execute javascript code.
You should execute your code after the page has loaded.
function onLoadHook(handler) {
if (window.addEventListener) {
window.addEventListener("load", handler, false);
}
else if (window.attachEvent) {
window.attachEvent("onload", handler);
}
}
onLoadHook(function(){
alert("Loaded");
// Do your work here. Create your ajax request and hook here.
});
Upvotes: 0
Reputation: 64526
Using content-disposition, you are outputting a file so the browser won't execute any JavaScript in the response because it is expecting the content of a file. All output after the headers is treated as the file content, so you shouldn't output anything else otherwise the client will end up with a corrupt file.
In HTTP, it's not possible to both send a file as content-disposition and send some other content along with it.
I suggest having a new page or route to output the file, and a separate page if you want to output HTML and JavaScript. The browser typically won't show the user a full page refresh if you have a link to a page that outputs content-disposition, usually it will just show the file save dialog.
Upvotes: 1