How to send data array to Asp.net core controller

Asked

Viewed 425 times

0

I have a screen where I have the registration of some items, in my control I am receiving the data of the array, but it is coming empty.

I already tried some options here on the forum, such as "JSON.stringify" and "JSON.parse".

Image of the reading of the data: inserir a descrição da imagem aqui

on my controller, I’m getting the data like this:

public IActionResult SaveOrder( string[] order)
{
    string result =  order.ToString();
    return Json(result);
}

  <script>

        function ExibirModalNovoProduto() {
            $("#ModalNovoProduto").modal('show');
        };

        // Adicionar pedido
        $("#addToList").click(function (e) {
            e.preventDefault();

            if ($.trim($("#productName").val()) == "" || $.trim($("#price").val()) == "" || $.trim($("#quantity").val()) == "") return;

            var productName = $("#productName").val(),
                price = $("#price").val(),
                quantity = $("#quantity").val(),
                detailsTableBody = $("#detailsTable tbody");

            var productItem = '<tr><td>' + productName + '</td><td>' + quantity + '</td><td>' + price + '</td><td>' + (parseFloat(price) * parseInt(quantity)) + '</td><td><a data-itemId="0" href="#" class="deleteItem">Remove</a></td></tr>';
            detailsTableBody.append(productItem);
            clearItem();
        });

        // Após adicionar um novo pedido na lista, limpar o formulário para Adicionar mais pedidos.
        function clearItem() {
            $("#productName").val('');
            $("#price").val('');
            $("#quantity").val('');
        };

          // Depois de adicionar um novo pedido à lista, se desejar, você pode removê-lo.
        $(document).on('click', 'a.deleteItem', function (e) {
            e.preventDefault();
            var $self = $(this);
            if ($(this).attr('data-itemId') == "0") {
                $(this).parents('tr').css("background-color", "#ff6347").fadeOut(800, function () {
                    $(this).remove();
                });
            }
        });

         // Coletar lista de pedidos múltiplos para o passe ao controlador
        $("#saveOrder").click(function (e) {
            e.preventDefault();

            var orderArr = [];
            orderArr.length = 0;

            $.each($("#detailsTable tbody tr"), function () {
                orderArr.push({
                    productName: $(this).find('td:eq(0)').html(),
                    quantity: $(this).find('td:eq(1)').html(),
                    price: $(this).find('td:eq(2)').html(),
                    amount: $(this).find('td:eq(3)').html()
                });
            });


        var dadosrecebido = JSON.stringify({
            name: $("#name").val(),
            address: $("#address").val(),
            order: orderArr
        });

            $.when(saveOrder(data)).then(function (response) {
                console.log(response);
            }).fail(function (err) {
                console.log(err);
            });
 
        });

    // Após clicar no botão Salvar, passe toda a exibição de dados para o controlador para salvar o banco de dados
    function saveOrder(dadosrecebido) {
        console.log(dadosrecebido);
        $.ajax({
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            type: 'POST',
            url: "/Orders/SaveOrder/?registros=" + dadosrecebido,
            success: function (result) {
                alert(result);
                location.reload();
            },
            error: function () {
                alert("Error!")
            }
        });
    };

    </script>

Final result; inserir a descrição da imagem aqui

1 answer

2


Good night. Make these changes and go testing one by one until it works: 1. When sending the date, do not send as "JSON.stringify({ data })", remove the "{}", will be as "JSON.stringify(data)", I’m sure that’s it. 2. Serialize JSON for a variable before performing POST. 3. Your controller will receive a single json to deserialize there, so swap the string array "string[] order" for "string order", this way you remove the redundant code.

  • Now it’s more a tip bro... The post does not return result, it only returns a 200 or 404... If your request expects something in return it is get.

  • Getting a little tipsy now... Please read this wikipedia page on the Http protocol: https://pt.wikipedia.org/wiki/Hypertext_Transfer_Protocol

  • tried many options and did not succeed, I will keep trying a solution

  • If you want to pass me your Discord you transmit your screen and I help you.

  • mine is itasouza#6189, I thank

  • with your help everything worked out, already added a positive response

  • Ai sim man! Just take a look at how Razor works... ajax is not necessary when using Asp . net.

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.