Pass an array from javascript to c#
Solution 1
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)
{
}
Solution 2
var xhr = new XMLHttpRequest();
xhr.open("POST", "mypage/SaveView");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.send(JSON.stringify({ myArray: someArray }));
Ovi
Updated on July 09, 2022Comments
-
Ovi almost 2 years
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.
-
Darin Dimitrov over 12 yearsNope, this won't work.
myArray=...
is invalid JSON. You have to stringify the entire literal. See my answer for an example. -
Darin Dimitrov over 12 yearsno, in this particular case you want JSON, otherwise the ASP.NET PageMethod that the OP is trying to invoke won't work. ASP.NET PageMethods expect JSON encoded requests and send JSON encoded results.
-
Raynos over 12 years@DarinDimitrov pagemethods don't work with "application/x-www-form-urlencoded" ?
-
Ovi over 12 yearsThank you, how should my webMethod look?
-
Darin Dimitrov over 12 years@Ovi, how do you expect me knowing this? It will depend on what you want this method to do. But the signature you have shown is correct and it will receive the
string[]
argument:[WebMethod] public static void SaveView(string[] myArray) { ... }
. -
FarligOpptreden over 12 yearsYour web method seems fine - you have to do with the array whatever your requirements specify. That's all up to you and we can't really help you with that. :)
-
Ovi over 12 yearsI edited my question can you please take a look? i also put in the correct method signature... Thank you!
-
Darin Dimitrov over 12 years@Ovi, you have completely changed your question. Where did you get that JSON from? How can you possible expect that this structure has anything to do with the
string[]
argument that your page method expects. You will have to define and adapt your signature if you want to receive an array of such structure. Lemme update answer. -
Ovi over 12 yearsThank you very much for updating your answer... but for some reason it is not working for me... i did every thing like you said...
-
Darin Dimitrov over 12 years@Ovi,
not working
is not a very precise problem description. Not one that allows me to help you any further. What is not working? What happens? Do you get some javascript error? Is the page method called? Do you see the AJAX request in FireBug? What does the server respond? Provide as much details as possible. -
Ovi over 12 yearsI get this error : localhost:50949/kWebGUI/ViewNQueryData.asmx/SaveView Failed to load resource: the server responded with a status of 500 (Internal Server Error)
-
Darin Dimitrov over 12 years@Ovi, and when you look at the HTML page returned by the server, what error message do you see?
-
Ovi over 12 yearshow do i look at the HTML page returned by the server?
-
Darin Dimitrov over 12 years@Ovi, but you have just said that the server returned 500 error. In the console window of FireBug you should normally see the AJAX request. Expand it and look at the Response tab. There you will see the exact HTML returned by the server.
-
Ovi over 12 yearsThe Response tab is empty... i see the ajax request but no response... :(
-
Darin Dimitrov over 12 years@Ovi, that's very weird, you are saying that the server sends 500 status code without response body? Hmm, no idea. Try removing some of the fields on your model. Try leaving only a single field and then add others progressively. Maybe it is a problem with the serialization. By the way have you enabled page methods by putting a ScriptManager and setting the
EnablePageMethods
property to true? -
Ovi over 12 yearsThat was a great idea!!!! i took of the
public SearchOption[] Searchoptions { get; set; }
and it worked fine, any idea why that sub array was making problems? -
Ovi over 12 yearsGood job!!!! it worked public SearchOption Searchoptions { get; set; }... with no array...
-
Darin Dimitrov over 12 years@Ovi, correct. I haven't noticed that SearchOption in your JSON is not an array. I have fixed the answer.
-
Ovi over 12 yearsone more question: now i need to send beside that model[] also a string, how do i modify the javascript, and the webMethod?
-
Ovi over 12 years@Darin Dimitrov, can you please help me with the last question?
-
Darin Dimitrov over 12 years@Ovi, you could use
JSON.stringify({ myArray: array, myString: 'foo bar' })
and then add amyString
parameter to your page method.