ajax调用其他方法 methods,Ajax的方法调用

I am trying to call a simple method in my code behind using Jquery with Ajax. But I get a 404 not found exception everytime. Unfortunately this is a web forms solution. So I dont have all the perks of MVC :(

It does get into the javascript method and gives the alert but won't go into my c# method. My previous experience of using this Jquery method is in an MVC website. Is it compatible with webforms sites?

My Javascript is:

$(document).ready(function() {

$('#btn_').click(function() {

var value = $('#twink').val();

something(value);

});

});

function something(theval) {

alert(theval);

$.ajax({

type: "POST",

url: "/Default.aspx/MyMethod?something=" + theval,

data: "{}",

contentType: "application/json; charset=utf-8",

dataType: "json",

success: function(msg) {

alert(msg);

}

});

}

}

And my C# code is:

public JsonResult MyMethod(string something)

{

JsonResult ret = new JsonResult();

return ret;

}

Thanks in advance.

解决方案

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:

[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 are not limited to simple argument types. You could use any type as input and output, it will be automatically JSON serialized.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值