Difficulty in picking up a certain type of return in c#

Asked

Viewed 183 times

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, got cute, the biggest difficulty is to get the data that send from an array via ajax.

Excerpt that I send 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 itensContract[0][id] it can get the right value, but since I don’t know how many itensContract has, I wanted to go through the url in such a way that I found the amount of itensContract[pos][id] and itensContract[pos][useUsed]

  • It needs to be via GET? If Asp.MVC, you can use instead of Request.QueryString, parameters within the method called in the controller. Example: public ActionResult NomeDoMetodoNoController (string [] itensContrato, string contrato, string codigoParceiro, string nomeParceiro, ...) { }. It is worth noting that the types of parameter go according to the parse made.

  • @Danielnicodemos but my real difficulty is to catch them via Request.Querystring

  • could post your controller?

  • I’ll take the risk of being ridiculed, but itensContrato[0][id]=4 does not seem to me an acceptable syntax for querystring. If you want to pass an array of compound objects, I suggest you do via POST

  • @Danielnicodemos sorry the years of delay, I just need to know how to get this itensContract syntax

  • @gabrielfalieri How are you doing with the QueryString What do you get? Are you turning into a class or are you picking up values on the nail so to speak?

  • @rodrigogq

Show 2 more comments

1 answer

4


I have some suggestions for you.

First, never treat JSON on the nail. On your side of C#, create a class that has exactly the same JSON data on 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. As soon as your template reflects exactly the data you are sending, you can use this code:

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

Try to play a little the variable jsonResultado so you can see the magic. You need to install the Newtonsoft.Json package first. After everything is objects in your C#, 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 there 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 how you are passing the data to the server. It does not follow the JSON standard. When we work with numeric values, there is no comma, as you are using. Every string needs to have an "scape".

Take this example: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/JSON

After you have started to see what a JSON is, try to see if your Querystring is returning a valid JSON. Otherwise you will face problems.

  • What happens, I’m using this Request.Querystring nail because I have to pass these parameters to protocol. Protocol Field = new Protocol(); ?

  • If you mount a JSON just like the class Protocolo on the server side, with the same names used in the class also on the Json side (like the example in the documentation I gave you), Jsonconvert.Deserializeobject will do the new Protocol() internally for you already, only that the difference is that it will come with the Javascript values already filled.

  • Turns out it’s not the same, it’s specific fields I send via javascript

  • In this case, I recommend that you create another class with the name ModeloProtocolo, and put in it what you have in Javascript. You can have several different templates to use to form different. There are people who divide into folders within the project. There are projects with the folder Models \ RequestModels \ ResponseModels, etc..

  • @gabrielfalieri It may seem like it’s going to take a little work to do this. But try it once so you see how easy it is at a lot. Make a command line console test project with only one class. Pass a string in the hand (a json) and try to deserialize to an object. Once you get the hang of it You implement it for real.

  • 1

    caraaaaaaaaaaaaaaaaaoo that easy, pqp

Show 1 more comment

Browser other questions tagged

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