Thursday, October 22, 2009

Calling PageMethod using jQuery

a simple example:



html code:

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
<script src="jquery-1.3.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
function CallPageMethod()
{
var msg = '<%= this.Message %>';

$.ajax({
type: "POST",
url: 'default.aspx/MyPageMethod',
contentType: "application/json; charset=utf-8",
data: "{msg:'" + msg +"'}",
dataType: "json",
success: function(result){alert(result.d);},
error: function(result){alert(result.d);}
});

}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:Button ID="Button1" runat="server" Text="Call Page Method" OnClientClick="CallPageMethod(); return false;" />
<asp:Button ID="Button2" runat="server" Text="Postback" onclick="Button2_Click" />
</form>
</body>
</html>


code-behind:



protected string Message;

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Message = "hellooo";
}
}

[System.Web.Services.WebMethod]
public static string MyPageMethod(string msg)
{
return msg;
}

protected void Button2_Click(object sender, EventArgs e)
{

}



Share/Save/Bookmark

No comments:

Post a Comment