How to Call server side C# asp.net code behind method/ function from client side code using ajax jquery/json js:
The below sample demonstrate how to call server side web method/function using jquery js not by javascript.
This sample code also shows how to call web method from asp.net button control (server side control) and HTML hyperlink anchor tag (client side control)
Sample ASPX source code:
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
<script src="js/jquery-1.6.4.min.js" type="text/javascript"></script>
<script type ="text/javascript">
$(document).ready(function () {
$('#<%=Button1.ClientID %>').click(function () {
$.ajax({
type: "POST",
url: "serversidecallfromjs.aspx/callServerMethod",
data: "{}", /*indicates no parametre is passed to web method/function*/
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function (msg) {
$('#msgDiv').text(msg.d);
}
})
return false;
});
});
function callm()
{
$.ajax({
type: "POST",
url: "serversidecallfromjs.aspx/callServerMethod1",
data: "{'parname': 100}" /*if any parametre is there means {'parname': 1}*/,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function (msg) {
$('#msgDiv').text(msg.d);
}
})
return false;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Click" />
<br />
<a href="#" onclick="callm();">Click 2 clock</a>
<br />
<div id="msgDiv"></div>
</div>
</form>
</body>
</html>
</div>
</form>
</body>
</html>
Code behind:
using System.Web.Services;
namespace MyWebApps
{
public partial class serversidecallfromjs : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string callServerMethod()
{
return "Response from server.";
}
[WebMethod]
public static string callServerMethod1(string parname)
{
return "Response from server" + parname + ".";
}
}
}
namespace MyWebApps
{
public partial class serversidecallfromjs : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string callServerMethod()
{
return "Response from server.";
}
[WebMethod]
public static string callServerMethod1(string parname)
{
return "Response from server" + parname + ".";
}
}
}
No comments:
Post a Comment