Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
通过按钮和javascript下载文件_Javascript_Asp.net Mvc - Fatal编程技术网

通过按钮和javascript下载文件

通过按钮和javascript下载文件,javascript,asp.net-mvc,Javascript,Asp.net Mvc,我有一个操作,它以以下方式返回(下载)excel文件: public IActionResult CreateExcelFile(string id, int xx, string start, string end) { //Some additional code... // .... // .... var file = File(doc, "application/vnd.ms-excel"); file.FileDownloadName = file

我有一个操作,它以以下方式返回(下载)excel文件:

 public IActionResult CreateExcelFile(string id, int xx, string start, string end) {

//Some additional code...
// ....
// ....
        var file = File(doc, "application/vnd.ms-excel");
        file.FileDownloadName = filename + " " + id + ".xlsx";
        return file;
}
到目前为止,我从这样的角度触发了这一行动:

<div id="myDiv">Some Content</div>
我进入调试模式,看到确实使用正确的参数调用了该操作,但是,在执行该操作后,不会返回(或下载)任何文件。我收到一条警告消息说“失败”,这表明响应未完成


知道我做错了什么吗?

不要使用ajax进行文件下载。对操作方法执行普通HTTP请求

$('#myDiv').click(function () {

    var start = $('#startDateTextBox').val();
    var end = $('#endDateTextBox').val();
    var url='/Customer/CreateExcelFile?id=FVM10000&xx=4&start='+start+'&end='+end;
    window.location.href=url;
});
我还建议使用HTMLHelper方法生成到动作方法基本部分的正确相对路径。您可以执行
Url.Action
helper方法,并将此调用的结果存储在div中的HTML5数据属性中

<div id="myDiv" data-url="@Url.Action("CreateExcelFile","Customer")">Some Content</div>

不需要对文件请求使用AJAX调用。只需打开一个新窗口“/Customer/CreateExcelFile”即可发送所需的参数。浏览器将下载或请求该文件。此文件的可能副本似乎有效!非常感谢。如何将参数引入此javascript?在视图中,我有一个要传递给JS的模型属性。如果CreateExcelFile操作方法中存在该参数,则可以将其添加到方法调用中。(例如:
@Url.action(“CreateExcelFile”,“Customer”,new{name=model.FirstName})
。既然url已经有了一个
,那么当你在js代码中连接querystring参数时,你应该首先启动
&
,而不是
。你完全正确。它很有效!非常感谢你!!@Shyju
<div id="myDiv" data-url="@Url.Action("CreateExcelFile","Customer")">Some Content</div>
$('#myDiv').click(function () {

    alert("Initiate excel export")
    var start = $('#startDateTextBox').val();
    var end = $('#endDateTextBox').val();
    var url=$(this).data("url")+"?id=FVM10000&xx=4&start="+start+"&end="+end;
    window.location.href=url;
});