Reputation: 7028
I have a problem in passing a JavaScript object to webmethod in asp.net.
The JavaScript object is:
var Materials = new Object();
function() {
Materials.MaterialName = $('[id*="txtMaterialName"]').val();
Materials.QuantityType = $('[id*="txtquantity"]').val();
AddNewMaterialToDb(Materials);
$(this).dialog('close');
}
Here materials is the object and now I want to pass it to a web method which takes a parameter of class type.
Now I have two option:
How to do that when I am using jQuery AJAX?
I mean to be specific how should I pass the jQuery object as data for jQuery AJAX so that any of the above two conditions gets satisfied?
Function for jQuery AJAX:
function AddNewMaterialToDb(materials) {
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'Services/Service.asmx/AddNewMaterial',
data :'{"Materials":"' + JSON.stringify(materials).replace('"', '\\\"') + '"}',
dataType: "json",
success: function(data, textStatus) {
if (textStatus == "success") {
if (data.d == true) {
alert('New Item Added');
}
}
},
error: function(data, textStatus) {
alert('An error has occured retrieving data!');
}
});
}
Upvotes: 4
Views: 32269
Reputation: 10374
Please see if this answer helps. Look especially at all the attributes that the service class and service method has.
EDIT: This article has some tips this question could use
Upvotes: 2
Reputation: 3175
you can do something like this:
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'Services/Service.asmx/AddNewMaterial',
data : { name: materials.MaterialName, quantity: materials.QuantityType } ,
success: function(data, textStatus) {
if (textStatus == "success") {
if (data.d == true) {
alert('New Item Added');
}
}
},
error: function(data, textStatus) {
alert('An error has occured retrieving data!');
}
});
Now in your asp.net Web method you can simple use Request.Form["name"]
to get the material name and Request.Form["quantity"]
to get quantity type. This way your web method will become generic and you wouldn't have to pass any parameters to your web method.
Upvotes: -1