简体   繁体   English

从JQuery函数获取数组到后面的C​​#代码

[英]Get array from JQuery function to C# code behind

I been trying to pass the output of a jquery function to my c# page code behind to do some processing and I cant figure out how to get it done properly but I know it must be possible. 我一直试图将jquery函数的输出传递给我的c#页面代码,以进行一些处理,但我想不出如何正确完成它,但我知道这是有可能的。

my Html code is as follows: 我的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> 

Please help me pass the 'items' var from the jquery function to my code behind, 请帮助我将jquery函数中的“ items”变量传递给我的代码,

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

There is an error in '{jsonString:' + items + '}' , because of string concatenation, you will get a string {jsonString:Hello World,How are you} , but JSON-valid string must be {"jsonString": "Hello World", "How are you"} . 由于字符串连接, '{jsonString:' + items + '}'存在错误,您将获得一个字符串{jsonString:Hello World,How are you} ,但是JSON有效字符串必须为{"jsonString": "Hello World", "How are you"}

Please use JSON.stringify to create JSON-valid string JSON.stringify({jsonString: items}) 请使用JSON.stringify创建JSON有效字符串JSON.stringify({jsonString: items})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM