开发者

Return tabledata as file with jquery and c# mvc

开发者 https://www.devze.com 2023-02-07 14:44 出处:网络
I would like to use jquery to send Table-data to the server and then get a data.csv file to download if i navigate to the url in my browser like this:

I would like to use jquery to send Table-data to the server and then get a data.csv file to download

if i navigate to the url in my browser like this: http://localhost:49400/File/Csv/?Text=qweerty&Filename=asdf i get promted with a file to download.

This is the action im calling:

    public FileResult Csv(FileModel fileModel)
    {
        return File(Encoding.UTF8.GetBytes(fileModel.Text), "text/plain", string.Concat(fileModel.Filename, ".csv"));
    }

and my javascript looks like this:

    $("table").click(function () {
        $.ajax({
            type: "POST",
            url: "http://localhost:49400/File/Csv/",
            data: {"Text": "qwerty", "Filename": "asdf"}
        })
    });

The response in firebug is containing the data, but i would like it to ask the user if it wants t开发者_如何转开发o download it, is this possible?


You cannot use AJAX to download a file.

Instead, you can just set location to a URL pointing to the file.
As long as the server returns a downloadable file (with a Content-Disposition header), the browser will show a Save dialog and will not replace the page.

If you want to download the file from a POST, you could make a hidden <form> that sends the POST, then submit() the form using Javascript.


you can't deliver file content through ajax call, perhaps find a way to construct URL with your table data as query string and stream the file that way or post-back the whole page and response as a stream

0

精彩评论

暂无评论...
验证码 换一张
取 消