简体   繁体   中英

using jquery ajax to send a complex object to a webmethod in a aspx page

I'm trying to send a complex object to my WebMethod in a aspx page (asp.net 4.0) using jquery 1.7.1 and json2.js

What I have accomplished is to send multiple parameters to a webmethod on the same page and now I want to wrap these parameters in an object instead.

So my WebMethod looks like this:

[WebMethod]
public static string ValidateControlInput(PairValue pair)
{
    var result = pair;
    return String.Format("Valid");
}

My javascript methods looks like this:

$(document).ready(ValidateInput);

function ValidatePairInput(codeId, descriptionId, labelId) {

var pair = CreatePairObject(codeId, descriptionId);
    SendDataToValidate(pair, labelId);
}

function SendDataToValidate(dataToValidate, controlId) {

$.ajax({
    type: 'POST',
    url: 'NewDocument.aspx/ValidateControlInput',
    contentType: 'application/json; charset=utf-8',
    data: dataToValidate,
    dataType: 'json',
    success: function (data, textStatus) {
        var result = data.d;
        DisplayValidationMessage(controlId, result);
    }
});

}

function DisplayValidationMessage(controlId, result) {
    $('#' + controlId).text(result);
}

function CreatePairObject(codeId, descriptionId) {
    var pair = { };
    pair.Code = $('#' + codeId).val();
    pair.Description = $('#' + descriptionId).val();    
    var DTO = { 'pair': pair };
    return JSON.stringify(DTO);
}

Sad to say, this does not work. I set a breakpoint in the webmethod, but that is never hit.

If I replace the code in the javascript method 'CreatePairObject' with this:

function CreatePairObject(codeId, descriptionId) {
    return JSON.stringify({ code: $('#' + codeId).val(), description: $('#' + descriptionId).val() });
}

and the webmethod with this:

[WebMethod]        
public static string ValidateControlInput(string code, string description)
{            
    return String.Format("Valid");
}

it works like a charm. So can anyone help me with this? Any help is much appreciated!

I think your problem is in the CreatePairObject function, you wrote Code and Description uppercase, and you'r nesting your JSON objects (what arrives to the webmethod is an object with a "pair" attribute containing the pair object). Try to serialize directly the pair object, instead:

function CreatePairObject(codeId, descriptionId) {
    var pair = { };
    pair.code = $('#' + codeId).val();
    pair.description = $('#' + descriptionId).val();    
    return JSON.stringify(pair);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM