繁体   English   中英

使用Ajax启动文件下载或不使用Ajax发布JSON

[英]Initiate file download with Ajax or Post JSON without Ajax

我的Ajax效果很好。 它发布到返回文件的C#控制器中。 不幸的是,我认为Ajax无法初始化文件下载。 我真的需要发布JSON。 JSON包含由用户应用于表的过滤器。 我尝试过将JSON作为字符串从输入中发布,但是它无法正常工作,并且从不填充我的对象。 我意识到以下我的C#代码除了返回文件外什么都不做,但是在我可以简单下载文件后,我将对其进行更多添加。

使用Javascript:

$.ajax(
    data: JSON.stringify(model),
    contentType: 'application/json',
    type: 'POST',
    url: 'Respondents/DownloadCSV',
    success: function () { alert('success'); },
    error: function () { alert('unsuccessful'); }
});

C#

[HttpPost]
public ActionResult DownloadCSV(RespondentViewModel model)
{
    string csv = "Name, Source, Email, City, State, Gender, Ethnicity, Age, Last Edit, Owner, Group, Status Date, Status";
    return File(new System.Text.UTF8Encoding().GetBytes(csv), "text/csv", "DispositionReport.csv");
}

我认为问题是网址,如下更改:

url: '/Respondents/DownloadCSV',

解决方案是:

返回带有url属性的json对象

{ redirect_url: '/blabla/path/to/file/download' }

成功通过Ajax通过JavaScript重定向到该URL

$.ajax(
    data: JSON.stringify(model),
    contentType: 'application/json',
    type: 'POST',
    url: 'Respondents/GetJsonResult', // !!!
    success: function (result) {
            if (result.redirect_url) {
                window.location = result.redirect_url;
            }
        },
    error: function () { alert('unsuccessful'); }
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM