Final Hazard Final Hazard - 2 months ago 5x
Javascript Question

Submit Form after linkbutton postback

I am seeing some strange interaction between my javascript and code behind page. Here is the page:

<form name="form1" id="form1" runat="server">
<button onclick="submitForm()">Submit Form</button>
<asp:LinkButton runat="server" OnClick="btn_download">Download!</asp:LinkButton>
<script type="text/javascript">
function submitForm()

and the code behind:

protected void btn_download(object sender, EventArgs e)
Response.ContentType = "application/octet-stream";
Response.AppendHeader("Content-Disposition", String.Concat("attachment; filename=", "download.txt"));
string hw = "hello world!";
byte[] info = new byte[hw.Length * sizeof(char)];
System.Buffer.BlockCopy(hw.ToCharArray(), 0, info, 0, info.Length);
Response.OutputStream.Write(info, 0, info.Length);

When I hit the download button I get a file as expected. After hitting download, if I hit the submit form button the form gets submitted but also it acts as though the download was pressed - triggering the btn_download method. If I comment out the code in btn_download(..) this does not occur.

If I hit the submit form button before hitting the download button it does not trigger btn_download. I tried commenting out the code behind line by line and it appears that the line Response.appendHeader(..) is causing the issue. Can someone explain what is going on here? Why does form1.submit() act as though I clicked download?


For an ASP.NET web form, you should avoid submitting the form with form.submit(). Instead, you should be calling __doPostback passing the name of the control which triggered the postback. Otherwise you're going to confuse the ASP.NET infrastructure which figures out which button or event triggered the submission of the form.

From the server's perspective, ASP.NET has no idea how the form was submitted (whether it was by the button or by your Javascript code) other than inspecting a hidden form variable "EVENTTARGET" When you click the download button first, doPostBack populates the event target and then submits the form; if you then call submit directly, the event target field still has a value in it leftover from the doPostBack call. As a result, ASP.NET thinks you clicked the download button again.

For more information, see Article: How to use doPostBack