I\'ve got a controller action that downloads a dynamically generated file:
public ActionResult DownloadFile()
{
var obj = new MyClass { MyStr
Here is how I redirected after the file is downloaded. The main logic is to wait the redirect until the file is downloaded. To do that, a server side response is calculated and redirect is delayed using server side response time + some offset.
Server Side Controller Code:
[HttpPost]
public ActionResult GetTemplate()
{
return Json(new {Url = Url.Action("ReturnTemplate") });
}
[HttpGet]
public ActionResult ReturnTemplate()
{
FileResult fileResult = // your file path ;
return fileResult;
}
Client Side Code:
<div id="btnGen" align="right"><button class="main-button" id="generateTemplate" type="Submit"></div>
Javascript:
$("#generateTemplate").click(function () {
var startTime = (new Date()).getTime(), endTime;
$.ajax({
url: '@Url.Action("GetTemplate", "Controller")',
type: 'POST',
traditional: true,
dataType: "json",
contentType: "application/json",
cache: false,
data: JSON.stringify(),
success: function (result) {
endTime = (new Date()).getTime();
var serverResponseTime = endTime - startTime + 500;
setInterval(function () { Back() }, serverResponseTime);
window.location = result.Url;
}
});
});
function Back() {
window.location = '@Url.Action("Index","Controller")';
}
Each HTTP request can only have one response - you're trying to sneak in two (the file, and a page).
Normally when you send a "Content-Disposition: attachment" HTTP header the browser will stay on the current page and pop a file save dialog (or automatically save the file in your downloads).
You're going to have to change your strategy if you want to prevent re-submission of the form. I'd suggest a bit of javascript to disable the form's submit button and show the "Completed" message in a div overlay?
As Ross has said, you can only return one response to a HTTP request. What i do in that case is:
RedirectToAction()
(POST, REDIRECT, GET pattern)window.location.href
property to an special download action which sends the file back to the browser