Send JS Array = {} in C # (WebMethod)

Actually, I have an Array declared on the JS side, as shown below:

 var benefArray = {};
 var benefCount = 0;
 var benefNome = $('#txtBenefNome').val();
 var benefDataNasc = $('#txtBenefDataNasc').val();
 var benefGrauParent = $('#txtBenefGrauParent').val();

 benefCount++;
 benefArray[benefCount] = new Array(benefNome, benefDataNasc, benefGrauParent);

              //Ajax Sender
            function sendAjax(url, parametros, sucesso) {
                $.ajax({
                    type: "POST",
                    url: url,
                    data: parametros,
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: sucesso
                });
            };

 sendAjax("Client.aspx/AddClient", "{benefArray: \"" + benefArray + "\"}",
 function (msg) {
                    var retorno = msg.d;
                    alert(retorno);
                });

On my side of C # WebMethod, I have:

    [WebMethod]
    public static string AddClient(object benefArray)
    {
        var t = benefArray;
    }

I am trying to get these values ​​from Javascript, what should I do? Any understanding of this would be appreciated! Thanks

+5
source share
2 answers

Start by defining a model that will represent the data that you work with so that you work with strong types and get rid of objectugliness by the method AddClient:

public class Benef
{
    public string Nome { get; set; }
    public string DataNasc { get; set; }
    public string GrauParent { get; set; }
}

then your web method will take an array of this model:

[WebMethod]
public static string AddClient(Benef[] benefs)
{
    // TODO: process ...

    // by the way as a result you could also return a strongly 
    // typed model and not only strings 
    // which could be easily manipulated on the client side
    return "some result"; 
}

and on the client you must define an array of parameters:

var parameters = { 
    benefs: [
        {
            Nome: $('#txtBenefNome').val(),
            DataNasc: $('#txtBenefDataNasc').val(),
            GrauParent: $('#txtBenefGrauParent').val()
        }
    ]
};

$.ajax({
    type: 'POST',
    url: 'Client.aspx/AddClient',
    data: JSON.stringify(parameters),
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    success: function(result) {
        alert(result.d);
    }
});

JSON.stringify, , . , json2.js script .

+10

,

[WebMethod]
public static string AddClient(Hashtable[] benefs)
{       
    var n = benefs["Nome"].ToString();
    return "some result"; 
}

.ToString(), Parse().

0

All Articles