How to export text data to csv using MVC 3?

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 contents, but does not open a window with the options "Save As" and "Open" ?? thanks

+4
source share
1 answer

Do not use AJAX to download a file. Use a regular link or button:

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

Now you can get rid of the javascript bit. The reason you cannot use AJAX to upload files is because the content will actually be transferred to the client, but you cannot open the Save As dialog from javascript.

+10
source

Source: https://habr.com/ru/post/1438585/


All Articles