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");

    }
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐