In asp.net application sometimes we need to call codebehind method from client script. In this post we will see how to call codebehind page method using jquery ajax.
To call codebehind page method from jquery we need to make method static.
Also we need to add [WebMethod] attribute for method. So the code behind method will look like:
[WebMethod]
public static string GetMessage()
{
return "Codebehind method call...";
}
We also need to add namespace using System.Web.Services; to add [WebMethod]
attribute to code behind method.
Now we can call this codebehind method using jquery ajax like
var loc = window.location.href;
$.ajax({
type: 'POST',
url: loc + "/GetMessage",
data: "{}",
contentType: "application/json; charset=utf-8"
})
.success(function (response) {
alert(response.d);
})
.error(function (response) {
alert(response.d);
});
Here using window.location.href we are getting url of aspx page and by appending method name to it we can call code behind method.
Below code demonstrats how to call codebehind method using jquery ajax and json
jQuery ajax call codebehind page method
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var loc = window.location.href;
$("#btnClick").click(function (event) {
$.ajax({
type: 'POST',
url: loc + "/GetMessage",
data: "{}",
contentType: "application/json; charset=utf-8"
})
.success(function (response) {
alert(response.d);
})
.error(function (response) {
alert(response.d);
});
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="btnClick" runat="server" Text="Button" />
</div>
</form>
</body>
</html>
Below is the code behind method that will get called by jquery ajax call:
using System;
using System.Web.Services;
namespace aspnetcontrol
{
public partial class jquerycallpagemethod : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string GetMessage()
{
return "Codebehind method call...";
}
}
}