【问题标题】:How can I Call Code Behind Method from JavaScript如何从 JavaScript 调用方法背后的代码
【发布时间】:2013-11-01 12:44:32
【问题描述】:

我有几天时间阅读和搜索这个问题的答案,但我没有找到。

我正在使用此代码

$('#Button1').click(function () {
            $.ajax({
                type: "POST",
                url: "/Default.aspx/ServerSideMethod",
                data: "{}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                async: true,
                cache: false,
            })
            return false;
        });
        });

用于尝试调用 C# 方法

[WebMethod]
 public void ServerSideMethod() {//Do something}

但我找不到任何可行的解决方案....

【问题讨论】:

  • 我认为您使用的是普通的 asp.net?!该方法在哪里存在?
  • 对不起...我正在使用 WebForms。方法在后面的代码中...
  • 向我们展示方法。我认为应该是static 并标有[WebMethod] 属性。
  • [WebMethod] 和静态方法的问题是我无法访问非静态方法并且可以管理数据库连接...我需要使用非静态方法...
  • 您不能对 webmethod 使用非静态方法,因此不能在方法本身的主体中使用非静态方法。

标签: c# javascript asp.net webforms


【解决方案1】:

要使其正常工作,请确保url 中设置的方法位置正确,并且该方法是publicstatic,并且添加了[WebMethod] 属性,例如:

[WebMethod]
public static void doAll()
{
    //do something
}

如果url 是“/Default.aspx/ServerSideMethod”,那么您的方法应该如下所示:

[WebMethod]
public static void ServerSideMethod()
{
    //do something
}

【讨论】:

  • 如何将数据传递给方法?例如,如果我希望该方法接收一个整数,我该怎么做?
  • 嗨!像这样public static void ServerSideMethod(int x) 然后在ajax post 中传递data 部分中的值。
  • 我必须使用 POST 吗?如果我使用“location.href”,我可以传递数据吗?
  • 你在用jquery吗?那么您将需要使用帖子,但由于我不知道您是怎么做的,您可以尝试搜索您需要的内容或提出问题。
【解决方案2】:

在 js 中试试这个:

$('#Button1').click(function () {
        // this calls default.aspx 
        $.ajax({
            type: "POST",
            url: '/Default.aspx',
            data: "{ServerSideMethod : '1'}", // send a parameter, to tell it what we want
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            async: true,
            cache: false,
            function(data){
                // data is json sent from server, if not, try $.parseJSON(data)
                // do something here after the server side code has finished
                if(data.ok){
                    //success from server side
                }
            }  
        });
        return false;
    });
    });

在 Default.aspx.cs 中:

    // fires anytime default.aspx is loaded
    protected void Page_Load(object sender, EventArgs e)
    {
        // check if is ajax call and not normal page load in the browser
        if (Request.Headers["X-Requested-With"] == "XMLHttpRequest")
        {
             Response.Clear();  //empty everithing so we don't send mixed content
             // no cache on ajax, IE caches ajas if this is missing
             Response.Cache.SetExpires(DateTime.Today.AddMilliseconds(1.0));
             Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);
             // here we are checking what we want to do, what client side asked
             if(!string.IsNullOrWhiteSpace(Request["ServerSideMethod"])) // this will be "1"
             {
                  doAll(); // do your work
             }
             Response.End();
        }
    }

    private void doAll() 
    {
            // do work, then send some json, as this is what you expect         
            // JavaScriptSerializer is located in System.Web.Script.Serialization
            Response.Write(new JavaScriptSerializer().Serialize(new { ok = 1, error = 0 }));
    }

【讨论】:

  • 根据您的建议,我可以从 javascript 访问代码并执行 ServerSideMethod(),虽然该函数的所有代码都已执行,但客户端发生了任何变化...
  • @omixam 我不明白你在说什么,我认为你想停止页面加载事件的其余部分?现在编辑也拥有它。
  • 我已经测试了几个小时这个建议,我发现我需要使用 UpdatePanel 来完成这项工作......但是在 UpdaatePanel 中,RowCommand 让它工作......
  • 其他观察应用程序永远不会进入 if (!string.IsNullOrWhiteSpace(Request["ServerSideMethod"])) 我评论了这一行...
  • @omixam 不需要为此使用 UpdatePanel。这是完整的。 UpdatePanel 只是将回发屏蔽为 ajax 请求,但 ajax 已经存在。
【解决方案3】:

首先我建议你写一些调试语句。在 doAll() 的第一行写一些输出。它实际上会让您知道您是否真的将请求从​​浏览器发送到您的服务器。我的意思是url: "/Default.aspx/ServerSideMethod", 是否有任何指向您的服务器的链接。我认为您正在执行 ajax 调用,但您根本没有启动服务器,或者没有将此 URL 链接到您的方法的侦听器。

【讨论】:

    【解决方案4】:

    如果你想从 ajax 调用非静态方法,我建议你创建一个 web 服务 并从 javascript 调用它。您可以在 Web 服务中使用非静态方法。

    Stackoverflow 中有很多关于如何从 javascript 调用 Web 服务的示例。 Call ASP.NET web service method from JavaScript

    【讨论】:

      【解决方案5】:

      asp.net 标记

      <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
      
      <html xmlns="http://www.w3.org/1999/xhtml">
      <head runat="server">
          <title></title>
      
      
      </head>
      <body>
          <form id="form1" runat="server">
          <%--
           you can remove dropdown if asp.net Render __doPostBack already for You.
          --%>
          <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True">
              <asp:ListItem>1</asp:ListItem>
              <asp:ListItem>2</asp:ListItem>
          </asp:DropDownList>
      
          <input type="button" value="Click Me" onclick="__doPostBack('CallFromJavaScript','Message from JavaScript')" />
      
          </form>
      </body>
      </html>
      

      和背后的代码。

      using System;
      using System.Collections.Generic;
      using System.Linq;
      using System.Web;
      using System.Web.UI;
      using System.Web.UI.WebControls;
      
      namespace WebApplication1
      {
          public partial class WebForm1 : System.Web.UI.Page
          {
              protected void Page_Load(object sender, EventArgs e)
              {
                  if (Page.IsPostBack)
                  {
                      string funcationName = Request.Params["__EVENTTARGET"];
                      string org = Request.Params["__EVENTARGUMENT"];
                      if (funcationName == "CallFromJavaScript")
                      {
                          CallFromJavaScript(org);
                      }
                  }
              }
      
      
              protected void CallFromJavaScript(string Data)
              {
                  Response.Write(DateTime.Now);
              }
      
      
          }
      }
      

      也许这个技巧对你有帮助

      【讨论】:

      • 那不行...我可以访问并执行该功能,但客户端站点发生了变化...
      猜你喜欢
      • 1970-01-01
      • 2013-09-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-06
      相关资源
      最近更新 更多