views:

344

answers:

2

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.

A: 

You are attempting to pass a string to the method. You will need to accept the string, and deserialize it with fx. JavascriptSerializer or JSON.NET

Luhmann
+1  A: 

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".

Josh
Ah... that actually makes sense. Just sending pt probably caused the deserializer to attempt to pass each property of the object to the webmethod as separate parameters.
David Lively