javascript - How to open file using Ajax in MVC -


i have hyperlink of file name , want download file retrieved database. can download file, form posted during process. instead of this, want form not posted of ajax, code hits error in ajax call. there smart way 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 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;     } } 

why not change link

<a href="@url.action("download", "controller", new { id = model.id })" >@model.filename</a> 

Comments