How to send a parameter to a C # method through an ajax call?

0

What I would like to achieve is to be able to pass a parameter from my javascript function through ajax but that said variable will reach my c # method that I am calling.

Ajax code:

$.ajax({
        url: "../../../pagina/configuracion/empresa/confEmpresa.aspx/getPlanta",
        data: { var1: 0},
        dataType: "json",
        type: "POST",
        contentType: "application/json; charset=utf-8"

I'm trying to do it this way but when I load the page I do not get information, before I got the information correctly, but I made this modification and it stopped working. Am I sending the variable incorrectly?

I have not seen any errors in the console and apparently the page load is broken because it does not show information, the server does not receive the parameter and therefore the method is not executed. if the request is successful I should show an accordion with all the plants of my company depending on the BD.

Code C #

 #region getPlanta
    [WebMethod]
    public static string getPlanta(int identificador)
    {
        string resultado = "";

            List<DataTable> listado = new List<DataTable>();
            Empresa empresa = new Empresa();
            resultado = empresa.getPlanta();
            string conteo = resultado.Substring(resultado.Length - 1);



            /**listado=getAutorizaciones(conteo);**/


        return resultado;
    }
    #endregion
    
asked by David 08.02.2017 в 16:19
source

2 answers

1

JavaScript

$.ajax({
        url: "../../../pagina/configuracion/empresa/confEmpresa.aspx/getPlanta",
        data: { var1: 0},
        dataType: "json",
        type: "POST",
        contentType: "application/json; charset=utf-8"

C #

public static string getPlanta(int identificador)

EYE! Because var1 != identificador will never send the data, always identifier on the server side will be null , to solve this, both variable names must be the same. Replace var1 with identifier.

    
answered by 08.02.2017 / 17:49
source
0

This is your function in JQuery:

function getData () {     if (validaCampos ()) {

    var oParam = "{ 'FechaIni': '" + $('#fechaIni').val() + "','FechaFin': '" + $('#fechaFin').val() + "' }";

    $.ajax({
        type: "POST",
        url: "Graficas.aspx/GetInformacion",
        data: oParam,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            var datos = $.parseJSON(msg.d);

        },
        error: function (msg) {

        }
    });
}

}

And so you invoke it from .NET:

[WebMethod]
public static string GetInformacion(string FechaIni, string FechaFin)
{
    PedidosBLL pBll = new PedidosBLL();
    return JsonConvert.SerializeObject(pBll.GetInformacion(FechaIni, FechaFin));
}
    
answered by 08.02.2017 в 17:32