javascript - 将参数从 ajax 函数传递到 aspx.cs 文件

标签 javascript c# jquery asp.net ajax

我已经用 HTML、JS 和 AJAX 创建了一些代码,但它无法按我希望的方式运行。

<script type="text/javascript">
function DeleteSelectedRecord(id) {
            alert(id);
            $.ajax({
                type: "POST",
                url: "PrintTasks.aspx/DeleteRecord",
                data: '{"id":"' + id + '"}',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function () {
                    alert("Deleted!");
                },
                failure: function () {
                    alert("Failure!");
                }
            });

        }
    function CreateATableFromDataBase() {
        var deserializedData = '<%=serializedList %>';
            deserializedData = JSON.parse(deserializedData);
            for (var i = 0; i < deserializedData.length; i++) {
                document.write(
                    "<tr>" +
                    "<th scope=\"row\">" + i.toString() + "</th>" +
                    "<th>" + deserializedData[i]["Name"] + "</th>" +
                    "<th>" + deserializedData[i]["Where"] + "</th>" +
                    "<th>" + deserializedData[i]["Destination"] + "</th>" +
                    "<th><input type=\"button\" class=\"btn btn-primary\" onclick=\"DeleteSelectedRecord(" + deserializedData[i]["Id"] + ")\" value=\"Delete\"/></th>" +
                    "</tr>"
                );
            }
    }
</script>

第二个函数将参数“id”传递给第一个函数。我已经使用警报方法来检查它是否至少正常工作。确实如此。当我想将参数传递给 PrintTasks.aspx.cs 文件中名为 DeleteRecord 的 super 方法时,问题就开始了...

[System.Web.Services.WebMethod]
    public static void DeleteRecord(int id)
    {
        very sophisticated code...
    }

里面有什么并不重要。最奇怪的是它不读取我的参数。

谢谢!

最佳答案

Just change This Line of code. It will work

 data: '{"id":"' + id + '"}',

Change to

 data: { id:id},

First id is the parameter name you set in .cs file method.. and second one is value you are going to pass...

关于javascript - 将参数从 ajax 函数传递到 aspx.cs 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31722687/

相关文章:

javascript - 如何在同一个域和同一个端口上托管多个 Meteor 应用程序?

javascript - 使用 span 代替 div 来显示省略号

c# - 将未知的 JSON 字符串转换为正确的对象

c# - 在 C# 中计算数组频率分布的最快方法是什么?

javascript - 计算数组中值为 True 的项目数

javascript - 如何将数组上的更改反射(reflect)到 lit-element 中渲染的 html 中?

c# - 调试由第 3 方可执行文件加载的 DLL

javascript - 在 textarea 中显示 ssh2 stdout 和 stderr

javascript - 使用 jquery 遍历列表到父项

javascript - "@"在 jquery ajax 数据中视为非法字符