开发者

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

I have a problem in passing a Ja开发者_开发技巧vaScript 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!');
    }
});
}


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜