I have an hyperlink of the file name and want to download the file retrieved from database. I can download the file, but the form is posted during this process. Instead of this, I want the form is not posted with the help of ajax, but my code hits error in Ajax call. Is there a smart way to achieve this?
View:
<a onclick="downloadFile(@Model.ID);" target="blank">@Model.FileName</a>
<script>
function downloadFile(id) {
$.ajax({
url: '@Url.Action("Download", "Controller")',
type: "POST",
data: JSON.stringify({ 'id': id }),
dataType: "json",
traditional: true,
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data.status == "Success") {
alert("Done");
} else {
alert("error occurs on the database level!");
}
},
error : function () {
alert("an error has occured!!!");
}
});
}
</script>
Controller:
public FileContentResult Download(int id)
{
var dataContext = repository.Attachments.FirstOrDefault(p => p.ID == id);
if (dataContext != null)
{
return File(dataContext.FileData, dataContext.FileMimeType);
}
else
{
return null;
}
}