Pass an array from javascript to c#
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) {
}
});
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.
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:
- The Content-Type request header must be set to
application/json
- The request payload should be JSON, for example:
{ myArray: [ 'foo', 'bar', 'baz' ] }
UPDATE:
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; }
}
and then:
[WebMethod]
public static void SaveView(Model[] myArray)
{
}
var xhr = new XMLHttpRequest();
xhr.open("POST", "mypage/SaveView");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.send(JSON.stringify({ myArray: someArray }));