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:
- either to define the webmethod to take a parameter of MaterialEntity class which would automatically understand the JSON string passed from the AJAX method
- to create the webmethod to take the JSON string and serialize into MaterialEntity class
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!');
}
});
}