【问题标题】:ASP.NET Webforms - Calling a C# method with AJAXASP.NET Webforms - 使用 AJAX 调用 C# 方法
【发布时间】:2016-01-18 10:14:14
【问题描述】:

我在一个 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 = "[" + ""  + "]";
        }
    }
}

【问题讨论】:

  • 添加错误消息会很有帮助。
  • 请为GetReport方法添加c#代码
  • 尝试使用 postman 之类的工具创建帖子,您将以可读的方式从服务器获得响应,以便您可以更轻松地进行调试。另外,您的函数称为 GetReport,并且您正在发送 POST,这听起来很奇怪,也许这是您的问题?
  • 请参阅"Should questions include “tags” in their titles?",其中的共识是“不,他们不应该”!

标签: javascript c# jquery asp.net ajax


【解决方案1】:

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

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

更多信息请关注this post。

编辑!!!

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

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

【讨论】:

  • 感谢您的回答。但是,我多次收到此错误:访问非静态字段方法或属性需要对象引用。
  • 分享你的错误截图会很有帮助:) 另外,创建一个非常简单的方法(只需返回一个int)并调用它,以证明你可以使用 AJAX 调用方法。我怀疑您的 C# 代码中有错误。
  • 我用另一种方法测试过,它可以工作(这个方法只返回一个控制台消息)。我原来的方法的问题是添加关键字静态下划线所有文本框,复选框,...在 aspx 中声明为非静态。
【解决方案2】:

您的方法必须是 static 并用 [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');
    }
});

【讨论】:

  • 感谢您的回答,但我的函数中没有使用任何参数。
  • JSON.stringify() 是我的页面方法能够读取数据所必需的。非常感谢 - 其他 SO 答案都没有字符串化答案!
【解决方案3】:

试试这种格式。

 [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

【讨论】:

  • 如果这是您的答案,则标记为该帖子的答案
  • 感谢您的回答。但是,我多次收到此错误(文本框、标签等 aspx 元素):访问非静态字段方法或属性需要对象引用。
  • 您需要通过 ajax 调用将文本框值作为参数传递并使用方法中的值。
【解决方案4】:

有3点必须检查:

  1. ajax 调用中的异步为真。示例:

    $.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. 如果代码隐藏初始方法调用 其他异步方法都必须是 标记为异步和静态。

【讨论】:

猜你喜欢
  • 2011-05-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-29
  • 1970-01-01
  • 2013-10-16
  • 1970-01-01
相关资源
最近更新 更多