[英]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.