我有一个页面,允许用户下载pdf格式的电子书。我已经编写了以下代码来执行下载。
控制器
[HttpPost]
public ActionResult Ebook(string url,string fileName)
{
try
{
//url="~/ebook/java.pdf"
string filePath = Server.MapPath(url);
Response.ContentType = "application/pdf";
Response.AppendHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(filePath));
Response.WriteFile(filePath);
Response.End();
return Json("success",JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
return Json("error", JsonRequestBehavior.AllowGet);
}
}
的Javascript
$(document).on("click", ".btnDownload", function () {
var downloadurl = $(this).data("download-url");
var fileName = $(this).data("file-name");
var href = $(this).attr("href");
$.ajax({
type: "POST",
url: href,
data: { url: downloadurl, fileName: fileName },
datatype: "json",
success: function (data) {
if (data = "success") {
bootbox.alert("Successfully downloaded the e-book");
}
else {
bootbox.alert("Cannot download this e-book");
}
},
error: function (err) {
bootbox.alert("Cannot download this e-book");
}
});
return false;
});
CSHTML
<table id="tblPartnerDetails" class="table table-bordered table-hover">
<thead>
<tr>
<th style="width:10px"></th>
<th>Course Name</th>
<th style="width:10px"></th>
</tr>
</thead>
<tbody>
@for (int i = 0; i < Model.StudentFeedback.Count; i++)
{
<tr>
<td>
@(i + 1)
</td>
<td>
@Model.StudentFeedback[i].Course.Name
</td>
<td>
<a class="btn btn-primary pull-left btn-xs btnDownload" href="@Url.Action("Ebook")" data-download-url="@Model.StudentFeedback[i].Course.CourseDownloadUrl"
style="margin-right: 5px;" data-file-name="@Model.StudentFeedback[i].Course.Name">
<i class="fa fa-download"></i> Download
</a>
</td>
</tr>
}
</tbody>
</table>
问题是文件没有下载,也没有显示错误信息。