使用部分视图更新UI以响应任务运行(异步)



我正在开发MVC C#Razor Framework 4.6。

我在Task.Run中封装了静态方法ExportManager.ExportExcelCannedReportPPR,用于长时间运行的报告。此方法返回boolean值,并在此基础上刷新部分视图(_NotificationPanel)。

public ActionResult ExportCannedReport(string cannedReportKey, string cannedReportName)
{            
    string memberKeys = _curUser.SecurityInfo.AccessibleFacilities_MemberKeys; //ToDo: Make sure this is fine or need to pass just self member?
    string memberIds = _curUser.SecurityInfo.AccessibleFacilities_MemberIDs; //ToDo: Make sure this is fine or need to pass just self member?
    string curMemberNameFormatted = _curUser.FacilityInfo.FacilityName.Replace(" ", string.Empty);
    string cannedReportNameFormatted = cannedReportName.Replace(" ", string.Empty);
    string fileName = string.Concat(cannedReportNameFormatted, "_", DateTime.Now.ToString("yyyyMMdd"), "_", curMemberNameFormatted);
    //ToDo: Make sure below getting userId is correct
    string userId = ((_curUser.IsECRIStaff.HasValue && _curUser.IsECRIStaff.Value) ? _curUser.MembersiteUsername : _curUser.PGUserName);
    var returnTask = Task.Run<bool>(() => ExportManager.ExportExcelCannedReportPPR(cannedReportKey, cannedReportName, fileName, memberIds, userId));
    returnTask.ContinueWith((antecedent) =>
    {
        if (antecedent.Result == true)
        {
            return PartialView("_NotificationPanel", "New file(s) added in 'Download Manager'.");
        }
        else
        {
            return PartialView("_NotificationPanel", "An error occurred while generating the report.");
        }
    }, TaskContinuationOptions.OnlyOnRanToCompletion);
    return PartialView("_NotificationPanel", "");
}

现在的问题是,即使执行了ContinueWith中的_NotificationPanel,UI也无法获得刷新。

问题是,一旦您从它返回,请求就完成了。一个请求不能多次返回。请求和响应是一对一的。您需要在这里使用asyncawait,这样当导出完成时,就会返回一个结果。

public async Task<ActionResult> ExportCannedReport(string cannedReportKey, 
                                                   string cannedReportName)
{            
    // Omitted for brevity...
    var result = 
        await Task.Run<bool>(() => 
            ExportManager.ExportExcelCannedReportPPR(cannedReportKey, 
                                                     cannedReportName, 
                                                     fileName, 
                                                     memberIds, 
                                                     userId));
    return PartialView("_NotificationPanel", 
        result 
            ? "New file(s) added in 'Download Manager'."
            : "An error occurred while generating the report.");
}

您需要使方法Task返回,使其"awaitable"。然后将该方法标记为async,从而启用await关键字。最后,您已经准备好执行长期运行的任务,并根据结果正确地确定并返回所需的部分视图更新。

更新

或者,您可以在客户端上使用AJAX调用,并在服务器响应后进行更新。有关详细信息,请查看MSDN。

最新更新