jQuery UI Dialog calling action that returns an Ht

2019-08-13 18:55发布

I have a custom controller extension to return an Excel file as an HttpContext response.

My controller action is as follows:

public ActionResult ExportToExcel()
{
    return this.Excel(headers, results, filename);
}

This works perfectly with a normal MVC callback.

I'm trying to create a jQuery UI dialog where the user can enter the file name and press Export. When the Export button is clicked the MVC action will get called in the controller, but the file doesn't get responded in the browser.

My dialog code is:

$("#export-excel").dialog({
            autoOpen: false,
            modal: true,
            title: "Export to Excel",
            buttons: {
                Export: function () {
                    $.post("/Search/ExportToExcel",
                    function () {
                        $("#export-excel").dialog("close");
                    });
                }
            }
        });

        $("#export-excel-button").click(function () {
            $("#export-excel").dialog("open");
            return false;
        });

And the html:

<div id="export-excel" style="display: none;">
    Filename:
    <input type="text" value="Results.xls"/>
</div>
<input type="button" value="Export" id="export-excel-button" />

2条回答
手持菜刀,她持情操
2楼-- · 2019-08-13 19:09

The problem is, that you call your action which returns the file data as an AJAX function.

You have to force the browser to make a regular request to your action to trigger the normal browsers download behavior.

The simplest way is to set the windows.location.href property in javascript:

buttons: {
     Export: function () {
         $("#export-excel").dialog("close");
         window.location = "/Search/ExportToExcel?...

A sidenote: you should use Url.Action() to generate the URL to your action.

查看更多
唯我独甜
3楼-- · 2019-08-13 19:29

How to allow download of file, that is returned as binary data from AJAX

I had same problem few days ago. You make AJAX call to your action, so your file is returned in callback function. If you change your button method for:

//...
Export: function () {
    $.post("/Search/ExportToExcel",
        function (myFileData) {
             $("#export-excel").dialog("close");
        });
    }

You will get binnary array of your file in myFileData parameter. I resolve this in that way:

Export: function () {
     $("#export-excel").dialog("close");
     window.location = "/Search/ExportToExcel?name=" + $('#filename').val();
}

<div id="export-excel" style="display: none;">
    Filename:
    <input id="filename" type="text" value="Results.xls"/>
</div>
<input type="button" value="Export" id="export-excel-button" />


public ActionResult ExportToExcel(string name)
{
     return this.Excel(headers, results, name);
}
查看更多
登录 后发表回答