2

I have a problem in downloading csv file using $.ajax(); code.

I have a controller which is returning the file as below.

public ActionResult ExportEx()
{
   StringBuilder sb = new StringBuilder();
        sb.Append("<table>");            
        sb.Append("<tr>");
        sb.Append("<td>1</td>");
        sb.Append("<td>2</td>");
        sb.Append("<td>3</td>");
        sb.Append("<td>4</td>");
        sb.Append("</tr>");
        sb.Append("<table>");         

    HttpContext.Response.AddHeader("content-disposition", "attachment; filename=student_" + DateTime.Now.Year.ToString() + ".xls");
    this.Response.ContentType = "application/vnd.ms-excel";
    byte[] buffer = System.Text.Encoding.UTF8.GetBytes(sb.ToString());
    return File(buffer, "application/vnd.ms-excel");
}

I have index.cshtml file as below

<input type="submit" value="Export To Excel" title="Export To excel" />        

<script type="text/javascript">
    $(".tt").click(function () {
        $.ajax({
            url: '/Home/ExportEx',
            type: 'POST',
            data: {},
            success: function (data) { },
            complete: function (data) { }
        });
    });
</script>

If I call using <a class="tt" href="@Url.Action("ExportEx", new { })">export</a> I can download csv file. But through $.ajax call i can not download.

Kindly help me in this.

Thanks in advance.

3
  • Why do this through ajax? Couldn't you just use an actionLink to download the file? Commented Apr 5, 2013 at 4:31
  • I need to pass some dynamic values to action method. So, I am using ajax call Commented Apr 5, 2013 at 9:40
  • You could use hidden form elements to pass dynamic values to the controller. I don't think ajax is the right approach here. Commented Apr 5, 2013 at 23:53

1 Answer 1

1
        $('button').click(function () {
            window.location.href = '/Home/ExportEx';
        });
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.