ASP.NET Webforms - Calling a C# method with AJAX

前端 未结 3 1327
-上瘾入骨i
-上瘾入骨i 2020-12-22 09:13

I\'ve an asp button on an aspx :



        
相关标签:
3条回答
  • 2020-12-22 09:33

    Try with this type of format.

     [System.Web.Services.WebMethod]
     public static void GetReport()
     {
     }
    
    
     [System.Web.Services.WebMethod]
     public static void GetReport(string name)
     {
     }
    

    Get more detail from

    http://www.aspsnippets.com/Articles/Call-ASPNet-Page-Method-using-jQuery-AJAX-Example.aspx

    0 讨论(0)
  • 2020-12-22 09:39

    Your method must be declared as static and decorated with [WebMethod]. So, your method should be:

    [WebMethod]
    public static void GetReport()
    {
        // Your code here
    }
    

    For more information, please take a look at this post.

    EDIT!!!

    I see you use some controls in your code (like txtInvoiceFrom, txtInvoiceTo). After making your method static, you cannot access those controls anymore. To solve this problem, please follow these steps (take txtInvoiceTo as an example):

    1. Don't get data by using txtInvoiceTo.Text or something similar. Pass it as a parameter.
    2. Get txtInvoiceTo data from client-side, using jQuery or something else (your choice), and pass it to the Ajax to post to server.
    3. To get txtInvoiceTo data by jQuery, you can do: $('#<%= txtInvoiceTo.ClientID %>').val()
    0 讨论(0)
  • 2020-12-22 09:44

    Your method must be static and decorated with [WebMethod] as below, why should make it static and decorate with [WebMethod]?

    [WebMethod]
    public static void GetReport()
    {
        // Your code here
    }
    
    $.ajax({
        type: "POST",
        url: "Selection.aspx/GetReport",
        data: JSON.stringify({ parametername : "Parameter Value" }),
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function()
        {
            alert('success');
        },
        error: function()
        {
           alert('error');
        }
    });
    
    0 讨论(0)
提交回复
热议问题