通过Ajax发送CSV

I'm trying to senda csv file opened with JS to the method written in C# where csv file will be parsed and added to database.

I have no problem with opening file and getting its contents. But whatever I do with my Ajax call I receive empty data in the method CreateFromFile. here you can see my code:

var a = fr.result;
$.ajax({
url: "/DeviceInstance/CreateFromFile",
type: "POST",
datatype: "html",
data: a,
error: function (data) {
    alert("Dodanie  nie powiodło się  Jeden lub wiecej numerów seryjnych nie są nikalne " + data);
},
success: function (data) {
    if (data.length > 0) {
        alert(data);
    }
    else {
        alert("Operacja zakonczona sukcesem")
    }
  }
});

and:

[HttpPost]
public JsonResult CreateFromFile(object data)
{

    return Json("Sukces");
}

I'm asking how should i modify my code to make things work?

here : fr.result:

samsung;galaxy ;s3;1234567
samsung;galaxy ;s4;54321
samsung;galaxy ;s5;34567yu8

Try the following (assuming your a payload is really a string):

$.ajax({
    url: '/DeviceInstance/CreateFromFile',
    type: 'POST',
    dataType: 'json',
    contentType: 'application/json',
    data: JSON.stringify({ dane: a }),
    /* callbacks */
});

And your controller action should now look like the following:

[HttpPost]
public JsonResult CreateFromFile(string dane)
{
    // Parse CSV data from "dane"
}

Hope this helps.

You could read the request input stream to access the body payload:

[HttpPost]
public JsonResult CreateFromFile()
{
    byte[] data = new byte[Request.InputStream.Length];
    Request.InputStream.Read(data, 0, data.Length);
    string csv = Encoding.UTF8.GetString(data);
    // ... do something with the csv

    return Json("Sukces");
}

Also in your AJAX request you seem to have specified datatype: "html". There are 2 problems with this:

  1. The parameter is called dataType instead of datatype.
  2. You specified html but your controller action returns JSON.

So that's very inconsistent thing. I would recommend you to get rid of this parameter and leave jQuery use the response Content-Type header to automatically infer the correct type.