如何在asp.net webforms中使用ajax

cho*_*obo 6 asp.net jquery

有没有办法使用ajax我正在使用Jquery这个用asp.net webforms而不必浏览页面生命周期?

Mun*_*Mun 9

根据您要执行的操作,您可以使用Web方法或Http Handler.Web方法可能更容易一些,只是服务器端静态函数,它们使用[WebMethod]属性进行修饰.

这是一个例子:

C#:

[WebMethod]
public static string SayHello(string name)
{
    return "Hello " + name;
}
Run Code Online (Sandbox Code Playgroud)

ASPX:

<asp:ScriptManager ID="sm" EnablePageMethods="true" runat="server"/>

<script type="text/javascript">
    #(function()
    {
        $(".hellobutton").click(function()
        {
            PageMethods.SayHello("Name", function(result)
            {
                alert(result);
            });
        });
    }
</script>

<input type="button" class="hellobutton" value="Say Hello" />
Run Code Online (Sandbox Code Playgroud)


Dav*_*ard 9

如果您正在使用jQuery,正如您所提到的,您可以使用jQuery直接调用Page Methods,而不会产生MicrosoftAjax.js及其生成的服务代理的开销以启用PageMethods.MethodName()语法.

给定一个静态[WebMethod]的装饰方法,PageName.aspx这就是所谓的MethodName,这是你如何可以调用它的客户端的例子:

$.ajax({
  type: "POST",
  url: "PageName.aspx/MethodName",
  data: "{}",
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  success: function(msg) {
    // Do something interesting with msg.d here.
  }
});
Run Code Online (Sandbox Code Playgroud)