I have a array in javascript and i need to get it to my c# webMethod. what is the best way to do this?
my c# code is like this:
[WebMethod]
public static void SaveView(string[] myArray, string[] filter)
{
}
EDIT--
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?
Thank you very much.
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:
application/json
{ 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 }));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With