Is there any way to use ajax I'm using Jquery for this) with asp.net webforms without having to run through the pages life cycle?
-
why would you want to do this ?BentOnCoding– BentOnCoding2011-03-16 21:27:45 +00:00Commented Mar 16, 2011 at 21:27
-
3Because going through the Page life cycle is pointless when all you need is some data retrieved or an action performed through AJAX.Mikael Östberg– Mikael Östberg2011-03-16 22:24:47 +00:00Commented Mar 16, 2011 at 22:24
4 Answers
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.
}
});
Comments
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" />
Comments
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.
Comments
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.