How to use ajax with asp.net web formats

Is there a way to use ajax, I use jquery for this) with asp.net web formats without having to execute the page life cycle?

+6
jquery
source share
4 answers

If you use jQuery, as you already mentioned, you can use jQuery to directly call page methods without incurring the overhead of MicrosoftAjax. js and the service proxy that it generates to enable PageMethods.MethodName() syntax.

Given the static [WebMethod] styled method in PageName.aspx called MethodName , this is an example of how you could call it 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. } }); 
+7
source share

Depending on what you are trying to do, you can use Web methods or Http handlers. Web methods can be a little simpler, and these are just server-side static functions that are decorated with the [WebMethod] attribute.

Here is an example:

FROM#:

 [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" /> 
+7
source share

Of course there is a way. Mark this answer . This particular example uses MVC on the internal server, but you can also do this with the underlying ASP.NET. Just take a look at calling PageMethods / WebMethods through AJAX .

One key is to declare a static method using the WebMethod attribute.

+1
source share

You can use page methods as they call.

They are essentially methods on 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 as follows from client scripts:

 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, as they can remain within the same web form features that a particular page is created.

+1
source share

All Articles