Passing Array of Strings to Webmethod with Variable Number of Arguments Using Jquery Ajax

Passing array of strings to webmethod with variable number of arguments using jQuery AJAX

Revised server-side code:

[WebMethod]
public string Concat(List<string> arr)
{
string result = "";
for (int i = 0; i < arr.Count; i++)
{
result += arr[i];
}
return result;
}

Also, add this above your WebService class declaration:

[System.Web.Script.Services.ScriptService]

Revised client-side code:

    $(document).ready(function () {

var myCars = new Array();
myCars[0] = "Saab";
myCars[1] = "Volvo";
myCars[2] = "BMW";

$.ajax({
type: "POST",
url: "WebService.asmx/Concat",
data: JSON.stringify({ arr: myCars }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: onSuccess,
failure: onError
});
});

function onSuccess(response) {
alert(response.d);
}

function onError() {
alert("fail");
}

Also, add above that script block a reference to JSON2, such as:

<script src="http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js"></script>

Notes:

  • I have tested this under .NET 4 and using jQuery 1.6.4.
  • Make sure you keep the client and server variable names in sync:
    public string Concat(List<string> arr)
    data: JSON.stringify({ arr: myCars })

Passing parameter to WebMethod with jQuery Ajax

Quick item:

your variable params
var params = '{ID:' + rowid + '}';
is a string.

So the line:
data: JSON.stringify(params), is redundant (or it should be).
Just set data: params,

Next up, on your web method, you converting your result to a JSON string and returning that as a string. If you web method class has ScriptMethod attribute, you don't need to do that.
Just return the data as the native type, and Asp.Net will do the conversion to JSON for you.

You might read the following articles:
http://elegantcode.com/2009/02/21/javascript-arrays-via-jquery-ajax-to-an-aspnet-webmethod/

http://encosia.com/2008/03/27/using-jquery-to-consume-aspnet-json-web-services/

Shortening The Number Of Arguments In A Web Method Using jQuery AJAX

NOTE: this example will not fully keep you from doing work, but you should only have to change a few places if something changes. Change the c# class and change the save method (and the layout perhaps).

Create an "address" class in c# with all the elements, create an array of addresses, then handle that list of addresses (single parameter) in the web method. My example is somewhat construed but should give you a starting place. I have not tested this fully but it should be close.

[WebMethod] 
public void SaveAddress(List<Address> Addresses) {
// save em here
}

public class Address
{
public Address()
{
streetAddress1 = streetAddress2 = apartmentNumber = city = state = zipCode = country = String.Empty;
}
public String streetAddress1 { get; set; }
public String streetAddress2 { get; set; }
public String apartmentNumber { get; set; }
public String city { get; set; }
public String state { get; set; }
public String zipCode { get; set; }
public String country { get; set; }
}

With this layout:

<div id='Address'>
<input class='streetAddress1' type='text'>
<input class='streetAddress2' type='text'>
<input class='apartmentNumber' type='text'>
<input class='city' type='text'>
<input class='state' type='text'>
<input class='zipCode' type='text'>
<input class='country' type='text'>
</div>
<div id='Address'>
<input class='streetAddress1' type='text'>
<input class='streetAddress2' type='text'>
<input class='apartmentNumber' type='text'>
<input class='city' type='text'>
<input class='state' type='text'>
<input class='zipCode' type='text'>
<input class='country' type='text'>
</div>
<button id='savedata'>SaveData</button>

Here is some client code to save:

function AddressRow(currentAddressRow) {
this.streetAddress1 = currentAddressRow.find('.streetAddress1').val();
this.streetAddress2 = currentAddressRow.find('.streetAddress2').val();
this.apartmentNumber = currentAddressRow.find('.apartmentNumber').val();
this.city = currentAddressRow.find('.city').val();
this.state = currentAddressRow.find('.state').val();
this.zipCode = currentAddressRow.find('.zipCode').val();
this.country = currentAddressRow.find('.country').val();
}

function AddressRowSet() {
var addressRows = [];
var allAddressRows = $('.Address');
var thisRow = null;
var currentRowCount = allAddressRows.length;
var i = 0;
for (i = 0; i < currentRowCount; i++) {
thisRow = allAddressRows.eq(i);
addressRows.push(new AddressRow(thisRow));
}
this.AddressRows = addressRows;
}

function SaveCurrentAddresses() {
var AddressRecords = new AddressRowSet();
var AddressesData = {
Addresses: AddressRecords.AddressRows
};
SaveAddressData(JSON.stringify(AddressesData));
}

function SaveAddressData(Addresses) {
$.ajax({
type: 'POST',
data: Addresses,
contentType: 'application/json',
url: '/WebServices/AddressService.asmx/SaveAddress',
dataType: 'json',
success: function(response) {
alert('address saved');
},
error: function(response) {
alert('error');
}
});
}
$('#savedata').click(function() {
SaveCurrentAddresses();
});

Passing an array to a web method in Javascript

In the aspx.cs, I needed to accept with type list not array. Thanks for the comments!

Pass Multiple Parameters from Jquery to ASPX web method not working

This answer is at first glance since i was not able to extract more info.

I hope this helps.

This is what your checkedvalue variable looks like in js code.

var checkedvalue = [];
var x = "230";//Just now constant value pass
var y = "450";
checkedvalue.push({
xCordi : x,
yCordi : y,
bPart:txtName.value
});

And this is your ajax request data.

data: JSON.stringify({ iName: ImageName,iPath:ImagePath,iData:checkedvalue })

Here is the method that is called with ajax.

public static void GetSaveData(string iName, string iPath, string[] iData)

Now i am not very familiar with ajax calling aspx. Usually there is a controller with MVC.

Since you don't mention the error in the original post.

My guess is you get a Null reference exception with checkedvalue->iData.
C# cannot deserialize a complex object from javascript without having the specifics. Meaning a c# object, it passes null.

An array of strings would work like this.

var checkedvalue = [];
checkedvalue.push("Hello"); //etc push other strings

You need a c# class like this one. Assuming they are of type string all three. From context i believe xCordi, yCordi are of type int feel free to change them. Also remove the "" from your js code.

public class SomeClass{
public string xCordi {get;set;} //change string to int
public string yCordi {get;set;} //change string to int
public string bPart {get;set;}
}

public static void GetSaveData(string iName, string iPath, string[] iData) -> public static void GetSaveData(string iName, string iPath, List<SomeClass> iData)
or public static void GetSaveData(string iName, string iPath, SomeClass[] iData)

Then your ajax method should work and c# should be able to deserialize the object.



Related Topics



Leave a reply



Submit