[英]Call C# server side from Javascript with parameter passing
我知道这个问题曾被问过,但到目前为止没有任何帮助我达成最终解决方案。
我有一个ASP网页,其中包含许多执行不同功能的按钮。 我还有一个包含对象列表的下拉框。 当我从下拉菜单中选择一项时,每个按钮的按钮功能都保持不变,但是我希望在C#代码中的服务器上调用该函数,该函数接收几个关键变量,然后可以将这些变量传递给API。 如果只能传递一个参数,则可以将其作为JSON字符串传递,因此这不是任何可能的解决方案都应考虑的限制。
我遇到的麻烦是确定执行此操作的最佳方法。 在使用AJAX调用,asp按钮中的OnCommand属性,WebMethods以及其他一些更晦涩的可能性方面,我已经读到了一些可能性。 我想避免使用隐藏域方法,因为它看起来确实很hacky。 话虽如此,如果人们确实认为这是最好的方式,我愿意改变想法。
我的代码的相关部分如下:
JavaScript代码
function testAJAX()
{
//The console.log was called successfully, however the ProcessData function was never hit correctly
/*console.log("hello");
PageMethods.ProcessData("Hello", successAjax, failAjax);*/
$.ajax({
type: "POST",
url: "UserManagement.aspx/ProcessData",
data: '{data:"Hello"}', // passing the parameter
contentType: "application/x-www-form-urlencoded; charset=utf-8",
dataType: "text",
success: function(retValue) {
// Do something with the return value from.Net method
alert(retValue);
}
});
}
function successAjax(response) {
alert(response.get_message());
}
function failAjax(response) {
alert(response.get_message());
}
C#代码(尝试从服务器上对数据+ =“进行调试”;)
[WebMethod(EnableSession = true)]
public static string ProcessData(string data)
{
data += " from the server";
return data;
}
调用Javascript代码
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" EnablePageMethods="true" runat="server" />
<button onclick="testAJAX()">Test AJAX</button>
</form>
在我的生命中,我根本无法在服务器端代码中遇到任何Ajax或Web Method调用击中我的断点的情况。 我努力了:
我真的很茫然,为什么它不能在服务器上调试,如果有人有任何建议,那将是很棒的。 我以为我缺少一些小东西,但这似乎足以阻止进度。 一旦可以调试,我应该会很高兴。 谢谢大家。
您没有正确传递数据
// data:"{data:Hello}", its not correct
删除并这样做
data: { data: Hello },
你可以像这样传递Hello变量
var Hello = "test";
$.ajax({
type: "POST",
url: 'UserManagement.aspx/ProcessData',
data: { data: Hello },
contentType: "application/json; charset=utf-8",
success: function (data) {
console.log(data);
},
failure: function (response) {
alert(response.d);
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.