roh*_*ngh 11 jquery json asp.net-ajax asp.net-mvc-4
以下是我的代码:
ActionResult DownloadAttachment(student st)
{
var file = db.EmailAttachmentReceived.FirstOrDefault(x => x.LisaId == st.Lisaid);
byte[] fileBytes = System.IO.File.ReadAllBytes(file.Filepath);
return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, file.Filename);
}
Run Code Online (Sandbox Code Playgroud)
这是我正在使用的脚本
$(function () {
$("#DownloadAttachment").click(function () {
$.ajax({
url: '@Url.Action("DownloadAttachment", "PostDetail")',
contentType: 'application/json; charset=utf-8',
datatype: 'json',
type: "GET",
success: function () {
alert("sucess");
}
});
});
});
Run Code Online (Sandbox Code Playgroud)
如何返回文件下载追求上面的代码?
我认为不需要Ajax调用你可以简单地使用超链接,如下例所示.
查看代码
<a href="@Url.Action("DownloadAttachment", "PostDetail", new { studentId = 123 })">Download Form</a>
Run Code Online (Sandbox Code Playgroud)
控制器方法
public ActionResult DownloadAttachment(int studentId)
{
// Find user by passed id
var file = db.EmailAttachmentReceived.FirstOrDefault(x => x.LisaId == studentId);
byte[] fileBytes = System.IO.File.ReadAllBytes(file.Filepath);
return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, file.Filename);
}
Run Code Online (Sandbox Code Playgroud)
请在ajax成功中试试这个
success: function () {
window.location = '@Url.Action("DownloadAttachment", "PostDetail")';
}
Run Code Online (Sandbox Code Playgroud)
更新的答案:
public ActionResult DownloadAttachment(int studentId)
{
// Find user by passed id
// Student student = db.Students.FirstOrDefault(s => s.Id == studentId);
var file = db.EmailAttachmentReceived.FirstOrDefault(x => x.LisaId == studentId);
byte[] fileBytes = System.IO.File.ReadAllBytes(file.Filepath);
return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, file.Filename);
}
Run Code Online (Sandbox Code Playgroud)
Ajax请求:
$(function () {
$("#DownloadAttachment").click(function () {
$.ajax(
{
url: '@Url.Action("DownloadAttachment", "PostDetail")',
contentType: 'application/json; charset=utf-8',
datatype: 'json',
data: {
studentId: 123
},
type: "GET",
success: function () {
window.location = '@Url.Action("DownloadAttachment", "PostDetail", new { studentId = 123 })';
}
});
});
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
61407 次 |
| 最近记录: |