weixin_33717117 2012-02-09 19:09 采纳率: 0%
浏览 48

mvc3 ajax导出文件

I have written an action to allow a user to export text as a .txt file. A button on the view calls this action through ajax. I used ajax because I want the user to stay on the same page while he downloads the text file. On the button click, the action gets executed. But it is not working as expected. The ajax call causes a page refresh and the file download popup is not showing up.

Can someone please help me fix this.

Here are the code snippets: View

<button id="exportButton">
<span>Export to Text</span>
@Html.HiddenFor(m => m.VersionId)
<input type="hidden" id="exportUrl" value='@Url.Content("~/LegalAgreement/_Export") ' />

<script type="text/javascript">

$(document).ready(function () {

    $("#exportButton").click(function () {

        $.ajax({
            url: $('#exportUrl').val(),
            type: 'post',
            cache: false,
            data:
        {
            id: $('#VersionId').val()
        },
            success: function () { return false; }
        }); //end ajax   

    });


});

Controller

 public ActionResult _Export(int id)
    {
       Response.AddHeader("content-disposition", "attachment; filename=fileName.txt");
        Response.ContentType = "application/octet-stream";

        System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
        byte[] extractedData = encoding.GetBytes("the text to be exported");

        return File(extractedData, "application/octet-stream");           
    }

SOLUTION

Thanks for all the responses!

I did not need to use ajax. This is the code that works as expected:

View

 <a id="exportButton" href='@Url.Action("_Export",new {id = Model.VersionId})'>
        <span>Export to Text</span>
 </a> 

Controller

 public ActionResult _Export(int id)
    {

        System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();          
        byte[] extractedData = encoding.GetBytes("some text");

        return File(extractedData, "application/octet-stream", "fileName.txt");

    }
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥20 有关区间dp的问题求解
    • ¥15 多电路系统共用电源的串扰问题
    • ¥15 slam rangenet++配置
    • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
    • ¥15 对于相关问题的求解与代码
    • ¥15 ubuntu子系统密码忘记
    • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
    • ¥15 保护模式-系统加载-段寄存器
    • ¥15 电脑桌面设定一个区域禁止鼠标操作
    • ¥15 求NPF226060磁芯的详细资料