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条回答

    报告相同问题?

    悬赏问题

    • ¥50 易语言把MYSQL数据库中的数据添加至组合框
    • ¥20 求数据集和代码#有偿答复
    • ¥15 关于下拉菜单选项关联的问题
    • ¥20 java-OJ-健康体检
    • ¥15 rs485的上拉下拉,不会对a-b<-200mv有影响吗,就是接受时,对判断逻辑0有影响吗
    • ¥15 使用phpstudy在云服务器上搭建个人网站
    • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
    • ¥15 vue3+express部署到nginx
    • ¥20 搭建pt1000三线制高精度测温电路
    • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况