简体   繁体   English

如何将字符串数组作为JSON参数传递

[英]How to pass a string array as a JSON argument

I'm trying to pass a couple of arguments to my JSON callback, however the string[] argument remains null. 我正在尝试将几个参数传递给JSON回调,但是string []参数仍然为null。 How do I need to pass the string array from javascript to get this working? 我需要如何从javascript传递字符串数组才能使它正常工作?

Javscript function: Javscript函数:

function jsonCallback(jsonCallbackID, argumentsArray) {
var argumentValues = [];
for (var i = 0; i < argumentsArray.length; i++) {
    argumentValues.push('' + $("#" + argumentsArray[i]).val());
}

// build request
var url = encodeURI("/DataEntry/JsonCallback/");
var data = ({ jsonCallbackID: jsonCallbackID, jsonCallbackValues: argumentValues, rndvalue: Math.floor(Math.random() * 10000000001) });

// fire request
$.getJSON(url, data, function (data) {});

The actual callback C# function: 实际的回调C#函数:

        public JsonResult JsonCallback(int jsonCallbackID, string[] jsonCallbackValues)
    { }

This function does get called however, argument 'jsonCallbackValues' is null. 但是确实会调用此函数,参数'jsonCallbackValues'为null。

EDIT 编辑

To get this working I did the following: 为了使此工作有效,我做了以下工作:

var data = ({ jsonCallbackID: jsonCallbackID, jsonCallbackValues: argumentValues.toString(), rndvalue: Math.floor(Math.random() * 10000000001) });

And split the jsonCallbackValues string at "," to get the resulting array. 并在“,”处拆分jsonCallbackValues字符串以获取结果数组。

You can give a try to JSON API ... 您可以尝试使用JSON API ...

var data = {
   jsonCallbackID:jsonCallbackID,
   jsonCallbackValues: JSON.stringify(argumentValues),
   rndvalue: Math.floor(Math.random() * 10000000001)
};
// your 
$.getJSON(url, data, function (data) {});

JSON is a serialized language, so you can't put objects inside. JSON是一种序列化语言,因此您不能在其中放入对象。

You should build your array in JSON format: 您应该以JSON格式构建数组:

jsonCallbackValues : ["value1", "value2"...] jsonCallbackValues:[“ value1”,“ value2” ...]

Try like this 这样尝试

var data = ({ jsonCallbackID: jsonCallbackID, jsonCallbackValues: $.toJSON(argumentValues), rndvalue: Math.floor(Math.random() * 10000000001) });

I have used a JSON jQuery plugin from http://code.google.com/p/jquery-json/ 我使用了来自http://code.google.com/p/jquery-json/的JSON jQuery插件

In the controller method change it to string jsonCallbackValuesArray 在控制器方法中将其更改为字符串jsonCallbackValuesArray

Then use JavaScriptSerializer orJSON.Net to convert the JSON string into String [] 然后使用JavaScriptSerializer或JSON.Net将JSON字符串转换为String []

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

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