How to iterate this javascript object in C # (or the correct way to send with AJAX) in ASP.NET

0

From a table where the user can add, delete and modify their values, you get a data type like the one shown below (which I can not change its format or data type) [here the code of the table ]:

var info = [{
            nombres: 'Juan',
            apellidos: 'Pérez',
            email: '[email protected]',
            pass: '123juan'
        }, {
                nombres: 'Julio',
                apellidos: 'López',
                email: '[email protected]',
                pass: 'passjulio'
        }];

But on the server side, it is obtained from Request.Params, when debugging and seeing the values obtained from the post, instead of arriving at the previous list as an array or object, each value arrives separately, which makes complex your iteration to then save them in the BD:

This is the driver code:

public JsonResult MiAction()
    { var x = Request.Params["info[]"];
        return Json("ok");
    }

And this is the form and the script:

function enviar_usuarios() {
       var info = [{
            nombres: 'Juan',
            apellidos: 'Pérez',
            email: '[email protected]',
            pass: '123juan'
        }, {
                nombres: 'Julio',
                apellidos: 'López',
                email: '[email protected]',
                pass: 'passjulio'
            }];
        var info2=[];
        info2[1] = info;
        $.ajax({
            data: { "info": info2 }, //datos que se envian a traves de ajax
            url: '/Home/MiAction', //archivo que recibe la peticion
            type: 'post', //método de envio

            success: function (response) {
                console.log(response);
            }
        });

    }

<input type="button" onclick="enviar_usuarios()" id="btn" value="Ir">

And this last are some attempts of solution that have not worked from the following variable

var info = [{
                nombres: 'Juan',
                apellidos: 'Pérez',
                email: '[email protected]',
                pass: '123juan'
            }, {
                    nombres: 'Julio',
                    apellidos: 'López',
                    email: '[email protected]',
                    pass: 'passjulio'
           }];

var formData = new FormData();
formData.append("lista", lista_JSON);

var formData = {"lista": lista_JSON, "lista2": [lista_JSON], "lista3": {lista_JSON}};

var formData = { lista: lista_JSON};
    
asked by Alex Lz 25.07.2018 в 02:42
source

3 answers

1

Looking at the structure of your Json, you can declare a class in the following way

public class Info
{
    public string nombres { get; set; }
    public string apellidos { get; set; }
    public string email { get; set; }
    public string pass { get; set; }
}

Then in the action of your controller, define the signature

[HttpPost]
public JsonResult MiAction(IEnumerable<Info> request)
{ 
    var info1 = request[0]; // primer elemento 
    return Json("ok");
}
    
answered by 25.07.2018 / 17:53
source
0

That would be according to what I told you:

function enviar_usuarios() {
       var info = [{
            nombres: 'Juan',
            apellidos: 'Pérez',
            email: '[email protected]',
            pass: '123juan'
        }, {
                nombres: 'Julio',
                apellidos: 'López',
                email: '[email protected]',
                pass: 'passjulio'
            }];
        var info2=[];
        info2[1] = info;
        $.ajax({
             JSON.stringify({ "info": info2 }), //datos que se envian a traves de ajax
           contentType: "application/json; charset=utf-8", 
           dataType: "json", 
            url: '/Home/MiAction', //archivo que recibe la peticion
            type: 'post', //método de envio

            success: function (response) {
                console.log(response);
            }
        });

    }
    
answered by 25.07.2018 в 04:40
0

At the end, according to the answers of Sergio Parra and Eduardo Valenzuela, within the AJAX the DATA line was modified and the action added more code to read and store that JSON, and it stayed like this:

    function enviar_usuarios() {
        var info = [{
            nombres: 'Juan',
            apellidos: 'Pérez',
            email: '[email protected]',
            pass: '123juan'
        }, {
            nombres: 'Julio',
            apellidos: 'López',
            email: '[email protected]',
            pass: 'passjulio'
        }];
        var info2 = [];
        info2[1] = info;
        $.ajax({
            data: { 'info': JSON.stringify({ 'info': info } ) }, //datos que se envian a traves de ajax
            url: '/Home/MiAction', //archivo que recibe la peticion
            type: 'post', //método de envio
            
            success: function (response) {
                console.log(response);
            }
        });

    }
<input type="button" onclick="enviar_usuarios()" id="btn" value="Ir" />

And inside the controller, the action and class that will store the received information would be:

 public class Usuarios
{
    public string nombres { get; set; }
    public string apellidos { get; set; }
    public string email { get; set; }
    public string pass { get; set; }
}

public class HomeController : Controller
{
    public JsonResult MiAction()
    {


        JsonTextReader reader = new JsonTextReader(new StringReader(Request.Params["info"]));
        while (reader.Read())
        {
            if (reader.Value != null)
            {
                Console.WriteLine("Token: {0}, Valor: {1}", reader.TokenType, reader.Value);
            }
            else
            {
                Console.WriteLine("Token: {0}", reader.TokenType);
            }
        }

        JObject jObject = JObject.Parse(Request.Params["info"]);
        // Obtener la propiedades result en una lista 
        IList<JToken> results = jObject["info"].Children().ToList();
        // Serializa resultados JSON a un objeto.NET
        IList<Usuarios> searchResults = new List<Usuarios>();

        foreach (JToken result in results)
        {
            Usuarios searchResult = JsonConvert.DeserializeObject<Usuarios>(result.ToString());
            searchResults.Add(searchResult);
        }

        // Lista las propiedades del resultado de la busqueda (IList)
        foreach (Usuarios item in searchResults)
        {
            Console.WriteLine(item.nombres);
            Console.WriteLine(item.apellidos);
            Console.WriteLine(item.email);
            Console.WriteLine(item.pass);
        }

        return Json("ok");
    }
    
answered by 25.07.2018 в 18:55