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 汇编语言除法溢出问题
    • ¥65 C++实现删除N个数据列表共有的元素
    • ¥15 Visual Studio问题
    • ¥15 state显示变量是字符串形式,但是仍然红色,无法引用,并显示类型不匹配
    • ¥20 求一个html代码,有偿
    • ¥100 关于使用MATLAB中copularnd函数的问题
    • ¥20 在虚拟机的pycharm上
    • ¥15 jupyterthemes 设置完毕后没有效果
    • ¥15 matlab图像高斯低通滤波
    • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗