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