Y
Y
Yana2017-10-24 12:31:42
ASP.NET
Yana, 2017-10-24 12:31:42

Why does Ajax return an error from a method?

Good afternoon.
There is a table which is filled dynamically. There is a button with ajax that passes data from the table to the controller method, then based on this data, you need to create Excel (or better, open an existing one and put this data there).
view with ajax

var testDataN = [{ "Date": "01.01.2015",  "Staff": "staff", "TypeTo": "DO", "Work": "work", "Tp": 6 }];
$.ajax({
    type: "POST",
    url: "/Naryad/ExportToExcel",
 

    data: JSON.stringify(testDataN),
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: successFunc,
    error: errorFunc


[HttpPost]
        public ActionResult ExportToExcel(Naryad[] testDataN)
        {


          var lines = new List<string>(testDataN.Length);
            foreach (var naryad in testDataN)
            {
               // lines.Add(string.Join("\t", naryad.Date, naryad.Staff, naryad.TypeTo, naryad.Work, naryad.Tp));
                lines.Add(string.Join("\t",naryad.Staff, naryad.TypeTo));
            }
          //  return View("\n", lines);
            string str = string.Join("\n", lines);
            
           

            StringBuilder sb = new StringBuilder();

            sb.AppendLine(str);
            Response.ClearContent();
            Response.ContentEncoding = Encoding.GetEncoding("Windows-1251");
            Response.ContentType = "applicationd/vnd.ms-excel";
            Response.AddHeader("Content-Disposition", "attachment; filename=csvfile.csv");
            Response.Write(sb.ToString());
            Response.Flush();
            Response.End();
            return View();

there are no errors in the debugger, the answer comes with the line that is needed, but in fact the file is not created and an error is returned from ajax (Error + line with data)
Help, please. I can't figure out what's the problem

Answer the question

In order to leave comments, you need to log in

2 answer(s)
Y
Yana, 2017-10-27
@ZyfMoXa

https://www.codeproject.com/Tips/1156485/How-to-Cr...
here is the solution to my problem. you never know who needs it
The problem was that the AJAX request is sent to the server, and the file tried to open on the client inside the callback. You can not do it this way. you need to create a file on the server (preferably temporary) and upload data there

D
Dmitry Kovalsky, 2017-10-24
@dmitryKovalskiy

Your query returns markup with an Excel file mixed in sideways.
Do you want to understand what they wrote heresy? Write a unit test for this functionality and you will see the problem right away.
The method should return not a View, but something like

return File(new MemoryStream(), "applicationd/vnd.ms-excel","fileName")
where instead of a MemoryStream there should be a stream with the contents of the file.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question