1

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)
{

}
1
  • i don't know where your javascript is being called, but I think you might want to look into the lifecycle of asp.net pages. Commented May 19, 2014 at 17:48

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Lol, this looks like a question from an exam. You nailed it! :)
0

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. 
});

1 Comment

Thanks.The problem is the page disappears immediately after the file finishes downloading. Still this code doesn't work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.