1

I've an asp button on an aspx :

<asp:Button id="btnReport2" name="btnReport2"  runat="server"  class="gradientBlueBtn" Text="Show Report" OnClientClick="Alert();" ToolTip="Report"/>

As you can see, I'm calling a javascript function which uses AJAX to call a C# method. I'm doing this way :

<script>
    function Alert()
            {
                $.ajax({
                    type: "POST",
                    url: "Selection.aspx/GetReport",
                    contentType: 'application/json; charset=utf-8',
                    dataType: 'json',
                    success: function()
                    {
                        alert('success');
                    },
                    error: function()
                    {
                        alert('error');
                    }
                });

            }
</script>

The thing is, I'm always getting the error message when I'm clicking on the button. Is there something I'm doing wrong?

EDIT : The C# method. I've put a breakpoint to see if the method is called but apparently it isn't.

public void GetReport()
{
    AddFilters();
    decimal localCurrencyRate;            
    App_Data.BulkImportDSTableAdapters.ClientsTableAdapter tadptClients = new  App_Data.BulkImportDSTableAdapters.ClientsTableAdapter();
    string legalEntityID = string.Empty;           
    if (txtSrcSys.Text != null)
    {
        DataTable dtSSYS = tadptClients.GetLegalEntityID(txtSrcSys.Text);
        if (dtSSYS.Rows.Count > 0)
        {
            legalEntityID = Convert.ToString(dtSSYS.Rows[0][0]);
        }
    }
    DateTime dtInvoiceFrom = DateTime.ParseExact(txtInvoiceFrom.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture);
    DateTime dtInvoiceTo = DateTime.ParseExact(txtInvoiceTo.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture);
    string strInvoiceFrom = String.Format("{0:yyyyMMdd}", dtInvoiceFrom);
    string strInvoiceTo = String.Format("{0:yyyyMMdd}", dtInvoiceTo);
    string localCurrency = dbcon.getLocalCurrency(legalEntityID);
    DataSet localCurrencyDs = dbcon.getCurrencyRate(localCurrency, strInvoiceFrom);
    if (Convert.ToDecimal(localCurrencyDs.Tables[0].Rows[0]["rate"]) == 0)
        localCurrencyRate = Convert.ToDecimal(localCurrencyDs.Tables[0].Rows[1]["rate"]);
    else
        localCurrencyRate = Convert.ToDecimal(localCurrencyDs.Tables[0].Rows[0]["rate"]);
    string fileQuery = string.Empty;
    if (cbxExpYes.Checked == true && cbxExpNo.Checked == false)
    {                
        fileQuery = File.ReadAllText(Server.MapPath("~/temp/Query.txt")).Replace("{1}", "XFORM_AREA.IMPORT_GE_MAIN_V15BIS m");
        fileQuery = fileQuery.Replace(":param1", localCurrencyRate.ToString());
        fileQuery = fileQuery.Replace("{0}", qb.getFilters().Replace("P.", "m."));
    }
    if (cbxExpYes.Checked == false && cbxExpNo.Checked == true)
    {               
        fileQuery = File.ReadAllText(Server.MapPath("~/temp/Query.txt")).Replace("{1}", "PREIMPORT_GE_MAIN m");
        fileQuery = fileQuery.Replace(":param1", localCurrencyRate.ToString());
        fileQuery = fileQuery.Replace("{0}", qb.getFilters().Replace("P.", "m."));
    }
    if (cbxExpYes.Checked == true && cbxExpNo.Checked == true)
    {               
        fileQuery = File.ReadAllText(Server.MapPath("~/temp/QueryUnion.txt"));
        fileQuery = fileQuery.Replace("{ParamValues}", "pg.DEFVAL ");
        fileQuery = fileQuery.Replace("{ParamTab}", "ref_var_def pg");
        fileQuery = fileQuery.Replace("{ParamCond}", "pg.NM = 'WL_REPORTING_CUR'");
        fileQuery = fileQuery.Replace("{0}", qb.getFilters().Replace("P.", "m."));
        fileQuery = fileQuery.Replace("{1}", qb.getFilters().Replace("P.", "i."));
    }
    ASPxPivotGrid1.OptionsFilter.ShowOnlyAvailableItems = true;
    int indexTravFullName = 0;
    int indexEndTravFullName = 0;
    string paramToRemove = string.Empty;

    indexTravFullName = fileQuery.IndexOf("AND PR.ST_TRAVELLER_FULL_NAME LIKE");
    if (indexTravFullName > 0)
    {
        indexEndTravFullName = fileQuery.Substring(indexTravFullName).IndexOf("AND", 3);
        paramToRemove = fileQuery.Substring(indexTravFullName, indexEndTravFullName);
        fileQuery = fileQuery.Replace(paramToRemove, string.Empty);
    }

    if (!string.IsNullOrEmpty(fileQuery))
    {


        DataSet dsTravels = new DataSet();

        oCmd.CommandText = fileQuery;
        oCmd.CommandType = CommandType.Text;
        oCmd.Connection = oConn;
        odpter.SelectCommand = oCmd;


        odpter.SelectCommand.Parameters.Add(":pSourceSystem", txtSrcSys.Text);
        odpter.SelectCommand.Parameters.Add(":pInvoiceFrom", strInvoiceFrom);
        odpter.SelectCommand.Parameters.Add(":pInvoiceTo", strInvoiceTo);

        if (!String.IsNullOrWhiteSpace(txtCustomNr.Text))
        {
            odpter.SelectCommand.Parameters.Add(":pCustomerNr", txtCustomNr.Text);
        }
        if (!String.IsNullOrWhiteSpace(txtIATA.Text))
        {
            odpter.SelectCommand.Parameters.Add(":Iata", txtIATA.Text);
        }
        if (!String.IsNullOrWhiteSpace(txtCurrCode.Text))
        {
            odpter.SelectCommand.Parameters.Add(":CurrCode", txtCurrCode.Text);
        }
        if (!String.IsNullOrWhiteSpace(txtInvoiceNrFrom.Text))
        {
            odpter.SelectCommand.Parameters.Add(":pInvoiceNrFrom", txtInvoiceNrFrom.Text);
        }
        if (!String.IsNullOrWhiteSpace(txtInvoiceNrTo.Text))
        {
            odpter.SelectCommand.Parameters.Add(":pInvoiceNrTo", txtInvoiceNrTo.Text);
        }
        if (!String.IsNullOrWhiteSpace(txtDossierNrFrom.Text))
        {
            odpter.SelectCommand.Parameters.Add(":pDossierNrFrom", txtInvoiceNrFrom.Text);
        }
        if (!String.IsNullOrWhiteSpace(txtDossierNrFrom.Text))
        {
            odpter.SelectCommand.Parameters.Add(":pDossierNrTo", txtInvoiceNrFrom.Text);
        }
        if (!String.IsNullOrWhiteSpace(txtTravellerName.Text))
        {
            odpter.SelectCommand.Parameters.Add(":pTravellerName", txtTravellerName.Text);
        }
        if (chbxSale.Checked)
        {
            odpter.SelectCommand.Parameters.Add(":pSale", "SA");
        }
        if (chbxRefund.Checked)
        {
            odpter.SelectCommand.Parameters.Add(":pRefund", "RE");
        }
        if (hfTravelWith.Value.Contains("chbxairs"))
        {
            odpter.SelectCommand.Parameters.Add(":pProductAir", "7");
        }
        if (hfTravelWith.Value.Contains("chbxhotels"))
        {
            odpter.SelectCommand.Parameters.Add(":pProductHotel", "3");
        }
        if (hfTravelWith.Value.Contains("chbxcars"))
        {
            odpter.SelectCommand.Parameters.Add(":pProductCar", "1");
        }
        if (hfTravelWith.Value.Contains("chbxrails"))
        {
            odpter.SelectCommand.Parameters.Add(":pProductRail", "6");
        }
        if (hfTravelWith.Value.Contains("chbxmisc"))
        {
            odpter.SelectCommand.Parameters.Add(":pProductMisc", "9");
        }

        if (!String.IsNullOrWhiteSpace(txtBatchNr.Text))
        {
            odpter.SelectCommand.Parameters.Add(":pBatchNr", txtBatchNr.Text);
        }


        odpter.MissingSchemaAction = MissingSchemaAction.AddWithKey;
        odpter.Fill(dsTravels, "ReportTab");
        int count = dsTravels.Tables[0].Rows.Count;
        DataTable dt = dsTravels.Tables[0];


        if (dt.Rows.Count > 0)
        {

            ASPxPivotGrid1.DataSource = dt;
            ASPxPivotGrid1.DataBind();
            Session["dtReport"] = dt;
            //ASPxPivotGrid1.Prefilter.CriteriaString = "[" + ""  + "]";
        }
    }
}
8
  • Adding the error Message would be helpful. Commented Jan 18, 2016 at 10:19
  • Please add you c# code for GetReport method Commented Jan 18, 2016 at 10:19
  • 1
    See stackoverflow.com/questions/27917255/… Commented Jan 18, 2016 at 10:20
  • 1
    Try creating the post with a tool like postman, you'll get the response from your server in a readable way so you can debug more easily. Also, your function is called GetReport, and you're sending a POST, which sounds wonky, maybe this is your problem? Commented Jan 18, 2016 at 10:21
  • 1
    Please see "Should questions include “tags” in their titles?", where the consensus is "no, they should not"! Commented Jan 18, 2016 at 10:23

4 Answers 4

6

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()
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for your answer. However, I'm getting this error multiple times : an object reference is required to access non-static field method or property.
Share a screenshot of your error would be really helpful :) Also, create a very simple method (just return an int) and call it, to prove that you can call methods using AJAX. I doubt that there are errors in your C# code.
I tested with another method and it works (this method only returns a console message). The problem with my original method is that adding the keyword static underlines all the textboxes, checkboxes, ... declared in the aspx as non-static.
5

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');
    }
});

2 Comments

Thanks for your answer but I'm not using any parameter in my function.
JSON.stringify() was necessary for my page methods to be able to read the data. Huge THANK YOU - none of the other SO answers have stringified answers!
1

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

3 Comments

If it's your answer then mark as answer for this post
Thanks for your answer. However, I'm getting this error multiple times (aspx elements such as textboxes, labels, ...) : an object reference is required to access non-static field method or property.
You need to pass text box value through ajax call as parameter and use those value from method.
1

There are 3 points that must be checked:

  1. async true in the ajax call. Example:

    $.ajax({
                           type: "POST",
                           url: "<%=System.Configuration.ConfigurationManager.AppSettings["URL"]%>ClassEadArquivos.aspx/deleteArquivo",
                           date: "{FileCode: '" +FileCode + "',CodigoAulaEad: '" + <%=CodigoAulaEad.Value%> + "'}",
                           async: true,
                           contentType: "application/json",
                           success: function (response) {
    
  2. static and async method in codebehind. Example:

    [WebMethod()]
    public static async System.Threading.Tasks.Task<string> deleteFile(string fileCode, stringCode ClassEad)
         {
    
  3. if the codebehind initial method calls other asynchronous methods must all be marked as asynchronous and static.

1 Comment

Hi and welcome to Stack Overflow! Please visit the help center for information on how to format code.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.