Joy
Joy

Reputation: 7028

Passing JavaScript object from jQuery AJAX to web method for custom serialization

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:

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

Upvotes: 4

Views: 32269

Answers (2)

Hari Pachuveetil
Hari Pachuveetil

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

Naveed Ahmad
Naveed Ahmad

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

Related Questions