Search code examples
javascriptc#jsonajaxasp.net-core

Sending JSON to C# controller using AJAX gives Count = 0 (.NET 7)


When I try to send a JSON to my controller I´m not receiving anything as a parameter.

This is my JavaScript:

var input = document.getElementById("input");

input.addEventListener('change', function () {
    const reader = new FileReader();
    reader.readAsText(input.files[0]);
    reader.onload = () => {
        const text = reader.result;
        var result = text.replace(/([0-9":])/g, '');
        result = result.split(/\r?\n/);
        console.log(result);

        var arr = new Array();

        result.map(function (element) {
            var cat = {
                'Name': element.replace(/[\u200B-\u200D\uFEFF]/g, '')
            };

            arr.push(cat);
        })

        jsonObject = JSON.stringify(arr);

        console.log(jsonObject);

        $.ajax({
            url: 'Categoria/BulkPost',
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            dataType: 'JSON',
            data: jsonObject,
            traditional: true,
            success: function () {
                alert('siuuuu');
            }
        });
    }
});

This is my controller:

[HttpPost]
public JsonResult BulkPost(List<Categoria> categorias)
{
    // Magic happens
}

My model:

[DataContract]
public class Categoria
{
    [Key]
    public int IdClas { get; set; }
    [Required]
    [DataMember(Name = "Name")]
    [DisplayName("Nombre de la categoría")]
    public string Name { get; set; }
}

And this is the generated JSON:

[
   {
      "Name":" Ayudas Funcionales"
   },
   {
      "Name":" EQUIPO MEDICO Y HOSPITALARIO"
   },
   {
      "Name":" Inventario"
   },
   ...
]

I've tried all the solutions that I've seen in other similar questions but none seems to work for me :(. Hope you can help me with this.


Solution

  • When I try to send a JSON to my controller I'm not receiving anything as a parameter.

    Actually, what @Serge has suggested is correct. By default ajax request type is application/x-www-form-urlencoded but you are sending json data, so merely List<Categoria> categorias signature in method wouldn't able to communicate with your controller method definition with your ajax json data request body.

    Most importantly, when sending request using ajax request body that must be decorated with [FromBody] because, [FromBody] attribute to a parameter to populate its properties from the body of an HTTP request and your controller action parameter expecting list in [FromBody] which mismatched with method signature.

    Correct controller action signature:

        [HttpPost]
        public JsonResult BulkPost([FromBody] List<Categoria> categorias)
        {
            //....rest of code 
        }
    

    Output:

    I have placed with correct [FromBody] attribute and working as expected, as you can see below:

    enter image description here

    enter image description here

    enter image description here

    Note: please refer to this official document if you want to know more details here.