0

I have a json result in my view,which I need to send it back to controller,to convert it to .CSV file,but I get null in controller even thought its contain data,here is my view the "result" contains data but in my controller I get it null,any help will be highly appreciated

  $.ajax({

        dataType: "json",
        type: "POST",
        url: "@Url.Action("CreateCSVFile", "Turbine")",
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify({ "result": result }),
        success: function (result) {
                        }
                        })

and here is my controller which I get NULL:

  public void CreateCSVFile(string result)
    {

        //XmlNode xml = JSON  JSON.DeserializeXmlNode("{records:{record:" + json + "}}"); 

        DataTable dt = JsonConvert.DeserializeObject<DataTable>(result);
        string strFilePath = @"C:\myCSVfile.csv";
        // Create the CSV file to which grid data will be exported.

        StreamWriter sw = new StreamWriter(strFilePath, false);

        //First we will write the headers.

        int iColCount = dt.Columns.Count;

        for (int i = 0; i < iColCount; i++)
        {
            sw.Write(dt.Columns[i]);
            if (i < iColCount - 1)
            {
                sw.Write(",");
            }
        }
        sw.Write(sw.NewLine);

        // Now write all the rows.

        foreach (DataRow dr in dt.Rows)
        {
            for (int i = 0; i < iColCount; i++)
            {
                if (!Convert.IsDBNull(dr[i]))
                {
                    sw.Write(dr[i].ToString());
                }
                if (i < iColCount - 1)
                {
                    sw.Write(",");
                }
            }
            sw.Write(sw.NewLine);
        }
        sw.Close();
    }
  • Try changing `data: JSON.stringify({ "result": result })` to this one: `data: $.param({ result: result })`. I think you don't need to use `JSON.stringify` unless you're passing complex object. Also, you need to change action method `public void CreateCSVFile` to `public ActionResult CreateCSVFile` and specify returned JSON data (you can't pass AJAX to `void` action method which returns nothing). – Tetsuya Yamamoto Dec 12 '17 at 08:10
  • @TetsuyaYamamoto I did what you said,but after changing to data: $.param({ result: result }) ,it even does not reach my controller!i put break point in controller but it dosnt reach there –  Dec 12 '17 at 08:21
  • Have you tried to change `void` to `ActionResult` as I suggested before? Controller action with `void` return type can't be directly accessed by AJAX callback, `ActionResult` return type does. – Tetsuya Yamamoto Dec 12 '17 at 08:24
  • @TetsuyaYamamoto I changed it yes,but still the same,and I changed my string in controller to jsonResult –  Dec 12 '17 at 08:36
  • Well, I sought the action method not included `HttpPost` attribute - try to add that like `[HttpPost] public ActionResult CreateCSVFile(string result) { ... }` since your AJAX callback expects POST action request. – Tetsuya Yamamoto Dec 12 '17 at 08:40
  • @TetsuyaYamamoto it reaches my controller now!but still null,i get jsonresult empty,really strange –  Dec 12 '17 at 08:50
  • You need to use this for JSON string: `return Json("yourJSONstringvalue")`, where JSON string value processed through viewmodel or collection. If you want to return CSV file from AJAX call, either use `FileResult` directly or create URL to other action which returns `FileResult`. – Tetsuya Yamamoto Dec 12 '17 at 08:53
  • @TetsuyaYamamoto can you please tell me how is the FileResult approach? yes I need to get the CSV file out json –  Dec 12 '17 at 08:57
  • `return File(new System.Text.UTF8Encoding().GetBytes(csvstringdata), "text/csv", "filename.csv");` is your main goal, right? There are plenty of examples to use `FileResult` returning CSV file, here's one of them to get started: https://stackoverflow.com/questions/4668906/export-to-csv-using-mvc-c-sharp-and-jquery. – Tetsuya Yamamoto Dec 12 '17 at 09:04

1 Answers1

0

This piece of code is working for me. I don't even include datatype and contenttype in my ajax request.

$.ajax({
    url: "Controller/MethodName",
    type: 'POST',
    data: { "bId": id, "status": stat },
    success: function (data) {
    }
});
    [HttpPost]
        public JsonResult CreateCSVFile(string bId, bool status)
        { 
            return Json(someReturn); 
        }

Hope this helps you. Good luck!

Zwei James
  • 73
  • 9