I'm a bit new to C# and javascript so while my question is specific I am open to any alternatives.
I have an array of values (that I have created in a javascript function) that I want to send to my code-behind file to be used in a method. From what I've researched using ajax and stringifying the array with JSON seems like the best method.
My questions are
Can I pass the array using this method?
How do I capture the information on the server side(in my code-behind?)
Javascript passing the values
var jsonvalues = JSON.stringify(values);
var callback = window.location.href
$.ajax({
url: callback
type: "POST",
contentType: 'application/json',
data: jsonvalues
});
I've seen many solutions using [WebMethod] or some kind of WebService to capture the data, can I use this to do work in my code-behind file without having to return data?
Here is what I'm using on my code-behind file
[WebMethod]
public static void done(string[] ids)
{
String[] a = ids;
}
An array can be created using array literal or Array constructor syntax. Array literal syntax: var stringArray = ["one", "two", "three"]; Array constructor syntax: var numericArray = new Array(3); A single array can store values of different data types.
The correct way to write a JavaScript array var txt = new Array("arr ","kim","jim"). JavaScript arrays are used to store multiple values in a single variable. Using an array literal is the easiest way to create a JavaScript Array.
The concat() method concatenates (joins) two or more arrays. The concat() method returns a new array, containing the joined arrays.
To save arrays or objects using the localStorage API in JavaScript, we need to first stringify the arrays or objects using the JSON. stringify() method, and when we need to retrieve the value we can use the JSON. parse() method.
I have written a in-depth example for this using ASP.NET MVC, but it can easily be adapted for WebForms.
Send data with jquery to an MVC controller
The HTML and jQuery will look almost exactly the same, with the exception of where you call the WebMethod.
If the page you are using is called Default.aspx
, and the method is called Done
, then your URL for the WebMethod will be Default.aspx/Done
.
<script>
// Grab the information
var values = {"1,","2","3"};
var theIds = JSON.stringify(values);
// Make the ajax call
$.ajax({
type: "POST",
url: "Default.aspx/Done", // the method we are calling
contentType: "application/json; charset=utf-8",
data: {ids: theIds },
dataType: "json",
success: function (result) {
alert('Yay! It worked!');
},
error: function (result) {
alert('Oh no :(');
}
});
</script>
Your WebMethod
will still be the same.
[WebMethod]
public static void done(string[] ids)
{
String[] a = ids;
// Do whatever processing you want
// However, you cannot access server controls
// in a static web method.
}
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