开发者

How to use ajax with asp.net webforms

Is there开发者_StackOverflow中文版 any way to use ajax I'm using Jquery for this) with asp.net webforms without having to run through the pages life cycle?


If you're using jQuery, as you mentioned, you can use jQuery to call Page Methods directly, without incurring the overhead of MicrosoftAjax.js and the service proxy it generates to enable the PageMethods.MethodName() syntax.

Given a static [WebMethod] decorated method in PageName.aspx that's called MethodName, this is an example of how you could call it on the client-side:

$.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.
  }
});


Depending on what you're trying to do, you could use Web Methods or Http Handlers. Web Methods might be a bit easier, and are just server side static functions which are decorated with the [WebMethod] attribute.

Here's an example:

C#:

[WebMethod]
public static string SayHello(string name)
{
    return "Hello " + name;
}

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


You can use Page Methods, as they are called.

They are essentially methods on a Page, but are declared as static.

public class MyPage : System.Web.UI.Page
{
   [WebMethod]
   public static string Reverse(string message) {
      return message.Reverse();
   }
}

They can then be used like this from client scripting:

function reverseMyString(message) {
   // Magically generated code appears
   PageMethods.SendForm(message, OnSucceeded, OnFailed);
}

function OnSucceeded(result) { alert(result) }
function OnFailed(error) { alert(error.get_message()) }

They are pretty neat compared to asmx web services since they can stay within the same Web Forms functionality that a particular page builds up.


There sure is a way. Check out this answer. That particular example uses MVC on the back-end, but you can similarly do it with basic ASP.NET - Just look into calling PageMethods/WebMethods via AJAX.

One of the keys is to declare a static method with the WebMethod attribute on it.


There sure is a way. Check out this answer. That particular example uses MVC on the back-end, but you can similarly do it with basic ASP.NET - Just look into calling PageMethods/WebMethods via AJAX

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜