C#MVC返回JSON或文件从AJAX调用 [英] c# mvc return JSON or File from AJAX call

查看:176
本文介绍了C#MVC返回JSON或文件从AJAX调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我看来是这样的:

        var url = '@Url.Action("DownloadZip", "Program")' + '?programNums=' + selectedRow;

        $.ajax({
            url: url,
            dataType: 'json',
            async: false,
            success: function (data) {
                if (data != "Successful") {
                    alert(data);
                }
            }
        });

该控制器可以返回一个文件,或者如果有错误可以返回一个JSON结果。
一直没能得到他们两个一起工作。

The controller can return a File or can return a JSON result if there was an error. Haven't been able to get them both work together.

下面是什么样子:

    public ActionResult DownloadZip(string programNums)
    {

        if(string.IsNullOrEmpty(programNums))
        {
          return Json("Error, blank info sent.", JsonRequestBehavior.AllowGet);
        }            

        var memoryStream = new MemoryStream();

        using (var zip = new ZipFile())
        {
            zip.AddFile("C:\\sitemap.txt");
            zip.Save(memoryStream);
        }

        memoryStream.Seek(0, 0);
        return File(memoryStream, "application/octet-stream", "archive.zip");

    }

我所看到的是,Ajax调用需要一个JSON值回。因为在我的情况,它返回一个文件,它不能正常工作。反正来处理我在做什么到可以给回一个JSON或从Ajax调用的文件。

What I am seeing is that the ajax call needs a JSON value back. Since in my case, it returns a File, it cannot work. Anyway to handle what I am doing to where it can give back a JSON or a File from the ajax call.

推荐答案

你有没有考虑回传JSON与文件网址?

Have you considered passing back JSON with a file Url?

如果成功找到该文件/创建。发回JSON结果与链接到该文件。然后在JavaScript中使用 windows.location 来检索文件。当有错误时,JSON结果将包含错误的信息和该信息可被显示给用户。对于这个工作,你需要创建另一个端点(动作),可以流的文件。

If the file is successfully found/created. Send back a JSON result with the link to the file. Then in javascript use windows.location to retrieve the file. When there is an error, the JSON result will contain the error information and this info can be displayed to the user. For this to work, you'll need to create another endpoint (action) that can stream the file.

这篇关于C#MVC返回JSON或文件从AJAX调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆