Search code examples
c#jqueryasp.net.netcode-behind

Calling a function in the .aspx.cs code behind file with jQuery load()


So I have something like this situation:

    $(document).on('click', 'a[data-link]', function () {
        var $this = $(this);
        url = $this.data('link');
        $("#imagePreview").load("imageProcess.aspx?" + url);

where url holds GET parameters. But imageProcess.aspx is different than the file I'm in (dashboard.aspx) and I need to reference some panels within my dashboard.aspx file. So my question is, using the .load() function, or even any function that could get the job done, how do I call a function, with GET parameters, in the dashboard.aspx code behind file? I'm fairly new to the .NET framework so I apologize if the question sounds elementary.


Solution

  • In your imageProcess.aspx.cs create a webmethod like:

    [WebMethod]
    public static string YourMethod(your parameters)
    {
    //Do Your Work
    }
    

    and in your dashboard page, in javascript use jquery to send request your webmethod like:

    $.ajax({
    type: "POST",
        url: "imageProcess.aspx/YourMethod",
        data: "{parameter1Name:'" + JSON.stringify(parameter1value) + "', Parameter2Name:'" + JSON.stringify(parmeter2Value) + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(data) {
    // do your success work, keep in mind that your returned data will be in data.d
        },
    error: function(XMLHttpRequest, textStatus, errorThrown) {
    // do your failuer work
    }
    });
    

    I hope it will give you a guidance to achieve your task.