Search code examples
asp.netjqueryvb.netpagemethods

Sending a complex object as parameter to Asp.Net PageMethod


I am trying to send an object created in JavaScript to an ASP.NET PageMethod. This object mirrors the properties of an existing custom business object, so i was hoping that i could pass a single object instead of a parameter for each property. I am getting an error "Unknown web method SavePart when attempting to use this method.

Javascript:

function() {
    var pt = { Id: 1, Onhand: 20, LowPoint: 30, __type: 'Custom.Objects.Part'};

    $.ajax({
        type: 'POST',
        url: 'partlist.aspx/SavePart',
        data: JSON.stringify(pt),
        contentType: 'application/json; charset: utf-8;'
        dataType: 'json',
        success: function(results) { alert('Success!'); }
    });
}

Code Behind:

<WebMethod()> _
Public Shared Function SavePart(pt as Custom.Objects.Part) as Boolean
    Dim repo as new PartRepository()
    return repo.Save(pt)
End Function

I am using another PageMethod which just accepts an int, and this works fine.


Solution

  • I ended up solving my problem by sending the object this way through the jQuery ajax command:

    data: '{"pt":' + JSON.stringify(pt) + '}'
    

    this serialized the object automatically and returned it to my WebMethod. When i tried sending the object as is, i got an error saying "invalid JSON primitive".