javascript - 在jquery ajax成功之前完成第一次调用

时间:2017-10-17 09:14:26

标签: javascript jquery ajax asp.net-mvc

我正在编写一个jQuery代码来下载文件,下载文件必须从服务器中删除。下面是我的文件下载和删除文件的代码。

if (method == "ValueAddedReportExportToExcel") {                
    $.ajax({
        async: false,
        type: "post",
        cache: false,
        url: '@Url.Action("ValueAddedReportExportToExcel", "report")',
        data: {
            fromDate: $('#txtFromDate').val(),
            toDate: $('#txtToDate').val(),
            reportForWhom: $("#ddlReportForWhom").val(),
            customers: (ddlCustomers != null) ? ddlCustomers.join(',') : "",
            salesReps: (salesReps != null) ? salesReps.join(',') : "",
            users: (users != null) ? users.join(',') : "",
            emailTo: emailTo,
            subject: subject,
            body: body,
        },
        success: function (data) {
            fileName = data.fileName;

            // call to download action.           
            window.location = '@Url.Action("Download", "Report")' + '?file=' + data.fileName;
            console.log('Success Call');
        },
        complete: function () {
            console.log('Complete Call');
            $.ajax({
                async: false,
                type: "post",
                url: '@Url.Action("DeleteFile", "Report")',
                data: { file: filename },
                success: function () {
                    alert(filename + ' is deleted successfuly. ');
                }
            });
        }
    });
    //methodURL = '@Url.Action("ValueAddedReportExportToExcel", "report")';
}

以下两个函数用于控制器中的下载和删除功能。

public virtual ActionResult Download(string file)
{
    string fullPath = Path.Combine(Server.MapPath("~/CostSavingReport"), file);
    byte[] fileBytes = System.IO.File.ReadAllBytes(fullPath);
    //return File(fileBytes, "application/vnd.ms-excel", file);
    return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, file);
}

public virtual void DeleteFile(string file)
{
    try
    {
        var fullPath = Path.Combine(Server.MapPath("~/CostSavingReport"), file);
        if (System.IO.File.Exists(fullPath))
        {
            System.IO.File.Delete(fullPath);
        }
    }
    catch (Exception)
    {
    }
}

现在问题是首先调用DeleteFile操作,而不是Download操作如何首先调用Download及之后调用DeleteFile

1 个答案:

答案 0 :(得分:3)

您可以为该操作创建自定义属性,如下所示,在执行方法后执行

public class DeleteFileAttribute : ActionFilterAttribute 
{ 
    public override void OnActionExecuted(ActionExecutedContext filterContext) 
    { 
        // Delete file 
    } 
} 

并将其用于您的行动

[DeleteFileAttribute]
public virtual ActionResult Download(string file)
{
    string fullPath = Path.Combine(Server.MapPath("~/CostSavingReport"), file);
    byte[] fileBytes = System.IO.File.ReadAllBytes(fullPath);
    //return File(fileBytes, "application/vnd.ms-excel", file);
    return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, file);
}
相关问题