【问题标题】:Get array from JQuery function to C# code behind从 JQuery 函数获取数组到后面的 C# 代码
【发布时间】:2019-06-07 14:54:25
【问题描述】:

我一直在尝试将 jquery 函数的输出传递给后面的 c# 页面代码以进行一些处理,但我不知道如何正确完成它,但我知道这一定是可能的。

我的Html代码如下:

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>jQuery Get Selected Radio Button Value</title>
    <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $("button").click(function () {
                var items = [];
                $.each($("input[name]:checked"), function () {
                    items.push($(this).val());
                });
                $.ajax({
                    url: 'WebForm1.aspx/LoadStrings',
                    method: 'post',
                    contentType: 'application/json',
                    data: '{jsonString:' + items + '}',
                    dataType: 'json',
                });
                alert("You entered: " + items.join(", "));
            });
        });
    </script>
</head>
<body>
    <h4>Please select your gender.</h4>
    <p>
        <label>
            <input type="radio" name="gender" value="male" />Male</label>
        <label>
            <input type="radio" name="gender" value="female" />Female</label>

        <br />
        <br />

        <label>
            <input type="radio" name="address" value="Kingston" />Kingston</label>
        <label>
            <input type="radio" name="address" value="Saint Catherine" />Saint Catherine</label>
    </p>
    <button type="button">Get Values</button>
</body>
</html>

请帮助我将 jquery 函数中的“items”变量传递给我的代码,

[WebMethod] 
public static string[] LoadStrings(string[] jsonString) { 

}

【问题讨论】:

  • 不要使用字符串连接创建 json 对象。将data: '{jsonString:' + items + '}' 更改为data: JSON.stringify({jsonString: items})

标签: javascript c# jquery asp.net ajax


【解决方案1】:

'{jsonString:' + items + '}'有错误,因为字符串拼接,你会得到一个字符串{jsonString:Hello World,How are you},但是JSON有效的字符串必须是{"jsonString": "Hello World", "How are you"}。

请使用JSON.stringify创建JSON有效字符串JSON.stringify({jsonString: items})

【讨论】:

  • 好的,我会做出改变的!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-06-13
  • 2012-12-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-06
  • 2011-11-07
相关资源
最近更新 更多