使用参数传递从Javascript调用C#服务器端

问题描述 投票:1回答:1

我知道之前已经提出过这个问题,但到目前为止还没有任何帮助我达成最终解决方案。

我有一个ASP网页,有许多按钮,执行不同的功能。我还有一个包含对象列表的下拉框。当我从下拉列表中选择一个项目时,按钮功能在每个按钮中保持不变,但是我希望在我的C#代码中在服务器上调用一个函数,该函数接收几个关键变量然后我可以传递给API。如果只能传递一个参数,我可以将其作为JSON字符串传递,因此这不是任何可能的解决方案应该关注的限制。

我遇到的问题是确定最好的方法。我已经阅读了一些可能性,比如使用AJAX调用,asp按钮内的OnCommand属性,WebMethods以及其他一些更加模糊的可能性。我想避免隐藏的现场方法,因为它看起来很糟糕。话虽这么说,如果人们真的认为这是最好的方式,我愿意改变我的想法。

我的代码的相关部分如下:

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方法调用我的断点。我努力了:

  • this中的顶部答案复制AJAX并更改变量以使其指向我的函数(url:“UserManagement.aspx / ProcessData”,)
  • 将我的脚本标记移动到body标记内
  • 将ScriptManager添加到表单中
  • 确保我没有使用Master页面显然改变了一些东西
  • 使用PageMethods.ProcessData()。这似乎是最接近的,因为它确实击中了成功函数,但似乎没有达到我的ProcessData函数...

我真的不知道为什么它没有在服务器上调试,如果有人有任何建议,这将是太棒了。我假设我错过了一些小的东西,但它似乎足以阻止进展。一旦我可以调试,我应该很高兴去。谢谢大家。

javascript c# asp.net ajax webmethod
1个回答
0
投票

您没有正确传递数据

// 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);
            }
        });
© www.soinside.com 2019 - 2024. All rights reserved.