Difficulty in getting a certain type of return in C #

3

I have a return that I send via Ajax that it returns in the URL as follows:

"http://localhost:11910/ProtocoloExterno/Inserir?itensContrato[0][id]=4&itensContrato[0][valorUsado]=150000,00&itensContrato[1][id]=9&itensContrato[1][valorUsado]=10050,00&contrato=4100001124&codigoParceiro=7900325&nomeParceiro=ORANGE COTE D%23IVOIRE S.A.&areaReclamacao=&codigoPatrimonial=5411050&operadora=Móvel&statusObra=&nFRN=&endereco=Rua Ursulina de Melo&estado=AM&cidade=78&descItem=desc&icms=15100,00&ipi=410,00&contaContabil=Capital não chamado&ordemInterna=Rua Ursulina de Melo&quantidade=1&valorUnitario=160050,00&valorTotal=160050,00&numeroPedido=11000110&itemPedido=10&observacao="

When I put Request.QueryString["endereco"]; for example, I get cute, the biggest difficulty is getting the data I send from an array via ajax.

Excerpt that I submit via javascript

$(document).on('click', "#btnSalvar", function () {

    var erros = 0;
    $("div").find('*').each(function () {
        var classe = $(this).attr("class");
        if (classe !== undefined) {
            var numItems = $('.has-error').length;
            if (numItems > 0) {
                return false;
            }
            else {
                //debugger;
                itensContrato = [];

               $("input:checked").each(function () {
                    var id = $(this).data("id");
                    var valorUsado = $(".txt" + id).val();
                    itensContrato.push({ id: id, valorUsado: valorUsado })

                });

               debugger;
                $.ajax({
                    type: 'GET',
                    url: 'Inserir',
                    dataType: 'JSON',
                    data: {
                        itensContrato: itensContrato,
                        contrato: $("#cmbContrato").val(),
                        codigoParceiro: $("#lblCodigoParceiro").html(),
                        nomeParceiro: $("#lblNomeParceiro").html(),
                        tipoContrato: $("#cmbTipoContrato").val(),
                        areaReclamacao: $("#lblAreaReclamacao").html(),
                        codigoPatrimonial: $("#txtCodigoPatrimonial").val(),
                        operadora: $("#cmbOperadora").val(),
                        statusObra: $("#cmbStatusObra").val(),
                        nFRN: $("#txtNFnr").val(),
                        endereco: $("#txtEndereço").val(),
                        estado: $("#cmbEstado").val(),
                        cidade: $("#cmbCidade").val(),
                        descItem: $("#txtDescricaoItem").val(),
                        icms: $("#txtICMS").val(),
                        ipi: $("#txtIPI").val(),
                        contaContabil: $("#lblContaContabil").html(),
                        ordemInterna: $("#txtOrdemInterna").val(),
                        quantidade: $("#txtQuantidade").val(),
                        valorUnitario: $("#txtValorUnitario").val(),
                        valorTotal: $("#txtValorTotal").val(),
                        numeroPedido: $("#txtNumeroPedido").val(),
                        itemPedido: $("#txtItemPedido").val(),
                        observacao: $("#txtObservacao").val()
                    }
                });
                return false;
            }
        }

    });
});

If I indicate a parameter as ContractItems [0] [id] it can get the correct value, but since I do not know how many ContractItems it has, I wanted to scroll through the url in such a way that I would find the quantity of contract items [pos] id] and itemsContract [pos] [valueUsed]

    
asked by anonymous 14.05.2018 / 16:41

1 answer

4

I have some suggestions for you.

First, never take JSON nail treatment. From your C # side, create a class that has exactly the same JSON data as the JavaScript side. Example:

public class ItemContrato { 
    public int Id { get; set; }
    public string ValorUsado { get; set; }
}

public class RetornoJson { 
    public ItemContrato [] ItensContrato { get; set; }
    public int CodigoParceiro { get; set; }
    public string NomeParceiro { get; set; }
    ...
}

This is called working with data models. Once your model accurately reflects the data you are submitting, you can use this code:

string jsonResultado = Request.QueryString...
var resultado = JsonConvert.DeserializeObject<RetornoJson>(jsonResultado);

Try to play around with the jsonResultado to see the magic. You need to install the Newtonsoft.Json package first. Once everything is in your C # objects, you no longer have to worry about the conversion itself ... and adding and removing elements becomes easier later.

In this documentation you will find more examples: Deserialize an Object

From here it will be easy to use the data:

var qtdContratos = resultado.ItensContrato.Count; // só não esqueça de ver se está null antes disso
foreach(var itemContrato in resultado.ItensContrato) {}

The second tip is the way you are passing the data to the server. It does not follow the JSON pattern. When we work with numeric values, there is no comma, as you are using. Every string must have a "scape".

See this example: link

Once you've started to see what a JSON is, try to see if your QueryString is returning a valid JSON. If not, you will face problems.

    
01.06.2018 / 20:59