ASP.NET Webforms - 使用AJAX调用C#方法

时间:2016-01-18 10:14:14

标签: javascript c# jquery asp.net ajax

我在aspx上有一个asp按钮:

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

正如您所看到的,我正在调用一个使用AJAX调用C#方法的javascript函数。我是这样做的:

<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>

问题是,当我点击按钮时,我总是收到错误消息。有什么我做错了吗?

编辑:C#方法。我已经设置了一个断点来查看该方法是否被调用但显然不是。

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 = "[" + ""  + "]";
        }
    }
}

4 个答案:

答案 0 :(得分:4)

您的方法必须静态,并使用 [WebMethod] 进行修饰,如下所示, 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');
    }
});

答案 1 :(得分:4)

您的方法必须声明为static并用[WebMethod]修饰。所以,你的方法应该是:

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

有关详细信息,请查看this post

修改!!!

我看到您在代码中使用了一些控件(例如txtInvoiceFromtxtInvoiceTo)。制作方法static后,您无法再访问这些控件。要解决此问题,请按以下步骤操作(以txtInvoiceTo为例):

  1. 不要使用txtInvoiceTo.Text或类似内容获取数据。将其作为参数传递。
  2. 使用txtInvoiceTo或其他内容(您的选择)从客户端获取jQuery数据,并将其传递给Ajax以发布到服务器。
  3. 要按txtInvoiceTo获取jQuery数据,您可以:$('#<%= txtInvoiceTo.ClientID %>').val()

答案 2 :(得分:1)

尝试使用这种格式。

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


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

获取更多详细信息

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

答案 3 :(得分:1)

有3点必须检查:

  1. ajax 调用中的 async true。示例:

    $.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. 代码隐藏中的静态和异步方法。示例:

    [WebMethod()]
    public static async System.Threading.Tasks.Task<string> deleteFile(string fileCode, stringCode ClassEad)
         {
    
  3. 如果代码隐藏初始方法调用 其他异步方法必须全部为 标记为异步和静态。