Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Send nested list to a controller in .NET 8

I’m using fetch to send data via POST to WebApplication controllers with this general function.

var postRequest = async (url, objeto) => {
    try {
        DATA = JSON.stringify(objeto);
        const respuesta = await fetch(url, {
            method: 'POST',
            body: DATA,
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            }
        });

        if (!respuesta.ok) {
            throw new Error(`Error en la solicitud: ${respuesta.status} - ${respuesta.statusText}`);
        }

        const response = await respuesta.json();
        return response;
    } catch (error) {
        console.error('Error al realizar la solicitud POST:', error);
        throw error;
    }

My goal is send "IdentificadorSesion", "Preguntas" atributes from this model.

using Aplicacion.DTOs;
using Dominio.Models;
using Microsoft.AspNetCore.Mvc.Rendering;

namespace WebApp.ViewModels
{
    public class ClientesVM
    {
        public ClientesVM()
        {
            DDLTiposRespuesta = new SelectList(new List<string>());
            DDLTiposDocumento = new SelectList(new List<string>());
        }

        public string IdentificadorSesion { get; set; }
        public string TipoDocumento { get; set; }
        public string NumeroDocumento { get; set; }
        public string NombreCompleto { get; set; }
        public string TipoBusqueda { get; set; }
        public DateTime FechaNacimiento { get; set; }
        public int Dia { get; set; }
        public int Mes { get; set; }
        public int Anio { get; set; }

        public WebApp.ViewModels.NegPreguntaDTO Preguntas { get; set; }
        public SelectList DDLTiposRespuesta { get; set; }
        public SelectList DDLTiposDocumento { get; set; }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WebApp.ViewModels
{
    public class NegPreguntaDTO
    {
        public int? Id { get; set; }
        public string? Respuesta { get; set; }
    }
}

So in order to do that I using postRequest like this

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

let preguntasRespondidas = [];
$('#FRMResponderPreguntas select').each(function (index, element) {
    let pregunta = {
        Id: index + 1,
        Respuesta: $(element).find('option:selected').val() || 'default_value'
    };
    preguntasRespondidas.push(pregunta);
});


let url = '@Url.Action("GetHTMLVerificacion", "Clientes")';
let data = {
    'IdentificadorSesion': sesionVerificacion,
    'Preguntas': preguntasRespondidas
};

const response = await postRequest(url, data);

An example of the petition payload generated by this function is

{
   "IdentificadorSesion":"cd20e10f-55f3-4bfd-a338-eb74fffafed3",
   "Preguntas":[
      {
         "Id":1,
         "Respuesta":"Ricardo Martínez López"
      },
      {
         "Id":2,
         "Respuesta":"6"
      },
      {
         "Id":3,
         "Respuesta":"Laura López Hernández"
      }
   ]
}

But data comes null to the controller

[HttpPost]
public async Task<JsonResult> GetHTMLVerificacion([FromBody] ClientesVM vm)
{

    var success = true;
    try{}
    catch (Exception ex){}

    return Json(new { success });

}

I have been testing and at least it works if I don’t send preguntas attribute in the petition body.

>Solution :

{"IdentificadorSesion":"cd20e10f-55f3-4bfd-a338-eb74fffafed3","Preguntas":[{"Id":1,"Respuesta":"Ricardo Martínez López"},{"Id":2,"Respuesta":"6"},{"Id":3,"Respuesta":"Laura López Hernández"}]}

The payload example you have shared has Preguntas as an array of objects but the property named Preguntas in the model class ClientesVM is not an array. You should make it an array type for the model binding to work.

public class ClientesVM
{
    .
    .
    .
    public WebApp.ViewModels.NegPreguntaDTO[] Preguntas { get; set; }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading