Ajax method call
Your method returns JsonResult
. This is MVC specific and you cannot use it in a webforms application.
If you want to call methods in the code behind in a classic WebForms application you could use PageMethods:
[WebMethod]
public static string GetDate()
{
return DateTime.Now.ToString();
}
And then to call the method:
$.ajax({
type: 'POST',
url: 'PageName.aspx/GetDate',
data: '{ }',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function(msg) {
// Do something interesting here.
}
});
And here's a full working example I wrote for you:
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Web.Services" %>
<script type="text/C#" runat="server">
[WebMethod]
public static string SayHello(string name)
{
return "Hello " + name;
}
</script>
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript" src="/scripts/jquery-1.4.1.js"></script>
<script type="text/javascript">
$(function () {
$.ajax({
type: 'POST',
url: 'default.aspx/sayhello',
data: JSON.stringify({ name: 'John' }),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg) {
// Notice that msg.d is used to retrieve the result object
alert(msg.d);
}
});
});
</script>
</head>
<body>
<form id="Form1" runat="server">
</form>
</body>
</html>
PageMethods are not limited to simple argument types. You could use any type as input and output, it will be automatically JSON serialized.