Please read the question before flagging as duplicate. I'm trying to download a file by redirecting with Javascript to a controller action in my ASP.NET MVC3 project. It works perfectly in Firefox and IE8. Here's my Javascript code:
<script type="text/javascript">
$(function(){
$(".pdf").click(function(e) {
e.preventDefault();
$.post("@Url.Action("PDF","Helper")", {id : @Model.ID} ,function(data){
if(data.message == "File not found.") {
alert(data.message);
} else {
location.href = '@Url.Action("PDF", "Helper", new { id = Model.ID })';
}
});
});
});
</script>
Here's what I tried:
I added
return false;
with all the things belowI changed the line to:
window.location.href = "../../Helper/PDF/@Model.ID";
I tried
window.location
insteadI changed relative link to full link
Tried without
window
Tried:
setTimeout(function() { document.location.href = '@Url.Action("PDF", "Helper", new { id = Model.ID })' },500);
I added the line:
window.event.returnValue = false;
it gave the error "window.event is not defined". I replaced it with
e
.I wrote "http://www.google.com" instead, and it didn't work too. However, it worked in a separate html file only consists of
location.href = "http://www.google.com";
.
All of this worked in IE8 and Firefox but not in Chrome. What can I do to resolve this?
EDIT: This is generated script:
$(function(){
$(".pdf").click(function(e) {
e.preventDefault();
$.post("/Helper/PDF", {id : 130405002} ,function(data){
if(data.message == "File not found.") {
alert(data.message);
} else {
location.href = '/Helper/PDF/130405002';
}
});
});
});
This is the generated HTML where I call the function:
<input class="pdf" type="button" value="Download File" />
Debugging the action I got these results; at the console Status is "failed". Type
is "application/pdf" as expected and Size
is 198 kb, it's the file size. Method is POST
.
This is my console output: