将数组从JavaScript传递到C#
我在javascript中有一个数组,我需要将其保存到我的C#webMethod中。最好的方法是什么?
I have a array in javascript and i need to get it to my c# webMethod. what is the best way to do this?
我的c#代码是这样的:
my c# code is like this:
[WebMethod]
public static void SaveView(string[] myArray, string[] filter)
{
}
编辑-
我的json数据如下:
My json data looks like this:
{"myArray":[{"name":"Title","index":"Title","hidden":false,"id":"1","sortable":true,"searchoptions":{"sopt":["cn","eq","bw","ew"]},"width":419,"title":true,"widthOrg":150,"resizable":true,"label":"Title","search":true,"stype":"text"},{"name":"Author","index":"Author","hidden":false,"id":"3","sortable":true,"searchoptions":{"sopt":["cn","eq","bw","ew"]},"width":419,"title":true,"widthOrg":150,"resizable":true,"label":"Author","search":true,"stype":"text"}]}
但是我不起作用...不知道为什么吗?
But i doesnt work... any idea why?
非常感谢。
您可以将其作为JSON字符串发送。这是使用jQuery的示例:
You could send it as a JSON string. Here's an example using jQuery:
var array = [ 'foo', 'bar', 'baz' ];
$.ajax({
url: '/foo.aspx/SaveView',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({ myArray: array }),
success: function(result) {
}
});
如果Page方法返回某些内容,则应使用 result.d 属性以获取页面方法调用的结果。
If your Page Method returns something, you should use the result.d
property in the success callback to fetch the result of the page method call.
如果您不使用jQuery,则必须手动进行帐户处理浏览器在发送AJAX请求方面的差异。但是,要使其正常工作,请求中必须包含2个关键内容:
If you don't use jQuery, you will have to manually account for browser differences in sending the AJAX request. But for this to work there are 2 crucial things to be included in the request:
- Content-Type请求标头必须设置为
application / json
- 请求有效负载应为JSON,例如:
{myArray:['foo', 'bar','baz']}
- The Content-Type request header must be set to
application/json
- The request payload should be JSON, for example:
{ myArray: [ 'foo', 'bar', 'baz' ] }
更新:
现在您已经更新了问题,似乎您不再愿意发送字符串数组。因此,定义一个与您要发送的JSON结构匹配的模型:
Now that you have updated your question it seems that you are no longer willing to send an array of strings. So define a model that will match the JSON structure you are sending:
public class Model
{
public string Name { get; set; }
public string Index { get; set; }
public bool Hidden { get; set; }
public int Id { get; set; }
public bool Sortable { get; set; }
public SearchOption Searchoptions { get; set; }
public int Width { get; set; }
public bool Title { get; set; }
public int WidthOrg { get; set; }
public bool Resizable { get; set; }
public string Label { get; set; }
public bool Search { get; set; }
public string Stype { get; set; }
}
public class SearchOption
{
public string[] Sopt { get; set; }
}
然后:
[WebMethod]
public static void SaveView(Model[] myArray)
{
}