4

I need to export text data to csv in MVC3. I do the following:

VIEW:

$(".export").click(function() {
    $.get("@Url.Action("Export","Log")");
});

CONTROLLER:

    public ActionResult Export()
    {
        var sb = new StringBuilder();

        var list = this.systemLogRepository.GetFilterList(
            null, this.ControllerContext.RequestContext.HttpContext.Request.QueryString, null);

        foreach (var item in list)
        {
            sb.AppendFormat(
                "{0},{1},{2},{3},{4}", item.Machine.Name, item.PackageID, item.ErrorDescription, item.OccurenceTime, Environment.NewLine);
        }

        return this.File(new UTF8Encoding().GetBytes(sb.ToString()), "text/csv", string.Format("Log-{0}.csv", DateTime.Now.ToString("g").Replace("/","-").Replace(":","_").Replace(" ", "-")));
    }

This returns the content but does not pop up a window with Save As and Open options ?? thanks

1
  • Can you try it out in different browsers? Commented Oct 9, 2012 at 7:47

1 Answer 1

9

Don't use AJAX to download a file. Use a normal link or a button:

@Html.ActionLink("export to CSV", "Export", "Log")

Now you could get rid of the javascript bit. The reason you cannot use AJAX to download files is because the content will indeed be transferred to the client but you cannot open a Save As dialog from javascript.

Sign up to request clarification or add additional context in comments.

3 Comments

Sometimes people are so overwhelmed with this jQuery thing that they simply forget how the web worked before jQuery and even before javascript. It always reminds me this cartoon: i.sstatic.net/ssRUr.gif
@DarinDimitrov: Your cartoon made me kept laughing continously for 5 mins!! :D
Im using asp.net mvc, but not razor. here what is the replacement for actionlink that can get data from controller and creates file without using ajax?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.