title: MVC download file using jquery post
body: <p>I'm trying to download an excel CSV file using jquery's $.post method but I'm having trouble getting it to work.</p>
  
  <p>I can see that the server is creating the file and sending it back to the client but after that, I can't get the file to actually download. </p>
  
  <p>My jquery post function looks like this:</p>
  
  <pre><code>$.post("/GenerateFile", { id: id, startDate: startDate, endDate: endDate }, function (data) {
  
      window.location = data;
  
  }).fail(function (XMLHttpRequest, textStatus, errorThrown) {
  
  });
  </code></pre>
  
  <p>And my server side function looks like this:</p>
  
  <pre><code>public async Task&lt;ActionResult&gt; GenerateFile(string id, string startDate, string endDate)
  {
      try
      {
          // My logic to create the file here, this is of type Task&lt;MemoryStream&gt;
          var outputFile = await CreateFile(sDate, eDate);
  
          return File(outputFile, "text/comma-separated-values", "Download.csv");
      }
      catch (Exception e)
      {
          return new HttpStatusCodeResult(400, e.Message);
      }
  }
  </code></pre>
  
  <p>When this data comes back to the client, it tries to navigate to a new page using the data from the CSV file (as can be seen on the URL link) with the message </p>
  
  <pre><code>Bad Request - Invalid URL
  
  HTTP Error 400. The request URL is invalid.
  </code></pre>
  
  <p>There is no problem with the file generation itself as I can create the file locally onto disk, it's just when I'm trying to use a browser to download it. </p>
  
  <p>I've seen guides which show this method working but there seems to be something that I'm missing that's stopping the download from working.</p>