控制器操作完成后,使用Javascript隐藏图像MVC3

时间:2012-07-26 16:07:03

标签: asp.net-mvc-3

我的应用程序已使用MVC 3,.net实现。 我想点击一个按钮生成一个excel文件。 使用Ajax调用控制器操作。 我的主要问题是:在文件生成期间,我试图在屏幕上显示图像,让用户知道进入操作。我可以很好地显示图像,但操作完成后我无法隐藏它。我使用的代码是:

Javascript代码:

$("input.DownloadExcelReport").click(function (e) {
   e.preventDefault();
   var parameter = -- code to fetch parameter value;
   var outputViewUrl = (the url is created here);
   showLoading(); -- This function displays the image
   window.location.href = outputViewUrl;
});

控制器操作代码:

public ActionResult DownExcelReportForAssortment(Guid parameter)   
{

       try
       {

           //the contents for the file generation are fetched here..   
           // Write contents to excel file
           if (memoryStream != null)
           {
                var documentName = "Report.xls";
                byte[] byteArrary = memoryStream.ToArray();
                return File(byteArrary, "application/vnd.ms-excel", documentName);
           }
       }
       catch (Exception ex)
       {
           LogManager.LogException(ex);
       }
}

我没有将Json结果返回给调用javascript方法,在那里我可以编写代码来隐藏图像。 我正在返回一个文件,该文件可以由用户保存并且操作已完成。

请知道,请帮我知道如何在文件生成操作完成后隐藏图像?

感谢帮助...

1 个答案:

答案 0 :(得分:10)

您可以结帐following article并将其投入使用。所以我们首先定义一个控制器:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    public ActionResult DownExcelReportForAssortment(Guid parameter, string tokenId)
    {
        // Simulate some heavy work to fetch the report
        Thread.Sleep(5000);

        // we fake it
        byte[] byteArray = System.IO.File.ReadAllBytes(@"c:\test.xls");

        var cookie = new HttpCookie("fileDownloadToken", tokenId);
        Response.AppendCookie(cookie);

        return File(byteArray, "application/vnd.ms-excel", "report.xls");
    }
}

并在视图中:

@Html.ActionLink(
    "download report",
    "DownExcelReportForAssortment",
    "Home",
    new { parameter = Guid.NewGuid(), tokenId = "__token__" },
    new { @class = "download" }
)

现在最后一步是包含jquery.cookie插件:

<script type="text/javascript" src="@Url.Content("~/scripts/jquery.cookie.js")"></script>

并编写脚本以订阅锚点击事件并跟踪下载进度:

$(function () {
    var fileDownloadCheckTimer;

    $('.download').click(function () {
        var token = new Date().getTime();
        $(this).attr('href', function () {
            return this.href.replace('__token__', token);
        });

        // Show the download spinner
        $('body').append('<span id="progress">Downloading ...</span>');

        // Start polling for the cookie
        fileDownloadCheckTimer = window.setInterval(function () {
            var cookieValue = $.cookie('fileDownloadToken');
            if (cookieValue == token) {
                window.clearInterval(fileDownloadCheckTimer);
                $.cookie('fileDownloadToken', null);

                // Hide the download spinner
                $('#progress').remove();
            }
        }, 1000);
    });
});
相关问题