您的方法返回JsonResult。这是特定于MVC的,您不能在Webforms应用程序中使用它。
如果要在经典WebForms应用程序中的代码后面调用方法,则可以使用PageMethods:
[WebMethod]
public static string GetDate()
{
return DateTime.Now.ToString();
}
然后调用该方法:
$.ajax({
type: 'POST',
url: 'PageName.aspx/GetDate',
data: '{ }',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function(msg) {
// Do something interesting here.
}
});
这是我为您写的一个完整的工作示例:
[WebMethod]
public static string SayHello(string name)
{
return "Hello " + name;
}
$(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);
}
});
});
PageMethods不限于简单的参数类型。您可以使用任何类型作为输入和输出,它将自动进行JSON序列化。