Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have a question about creating JSON from JQuery, sending the same by Ajax to a webservice in .NET, and how to deserialize in .NET and save to the database.

Maybe someone can give me a hand to see where I'm mistaken!

jQuery and JSON:

var myObject = {};

//** BusinessPartner **
//function BusinessPartner(prefix) {
//    this.bpCodigo = $(prefix + " option:selected").val();
//    this.bpNombre = $(prefix + "-infonombre").text();
//
//** Locations **
//function Locations(prefix) {
//    this.locCode = $(prefix + " option:selected").val();
//    this.locName = $(prefix + "-name").text();

var oNewObject = new BusinessPartner("#bp-01");
var oNewObject2 = new BusinessPartner("#bp-02");

var myLocation = [];
var oOrigin = new Locations("#receipt");
myLocation.push(oOrigin);
var oDestination = new Locations("#portloading");
myLocation.push(oOrigin);

myObject["Agent1"] = oNewObject;
myObject["Agent2"] = oNewObject;
myObject["Locations"] = myLocation;

$.ajax({
    type: "POST",
    url: "Services/ActionsDb.asmx/saveData",
    contentType: "application/json; charset=utf-8",
    data: JSON.stringify(myObject),
    datatype: "json",
    success: function (response) {
        // After correct save send OK message.
    },
    error: function (xhr, status) {
        alert("An error occurred: " + status);
    }
});

The class in C# .NET

As I understand it, that should have exactly the same format as JSON received by the webservice.

public class Agent
{
    public string bpCodigo { get; set; }
    public string bpNombre { get; set; }
}
public class Location 
{
    public string locCode { get; set; }
    public string locName { get; set; }
}
public class oGet
{
    public Agent oCliente { get; set; }
    public Agent oCliente2 { get; set; }
    public List<Location> oLocations { get; set; }
}

Webservice

Good, now the WebService ActionsDb.asmx / savedata that will be asked to save the data in the DB.

    [WebMethod(EnableSession = true)]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public string saveData(oGet myObject)
    {
        try
        {
            string sClienteName = myObject.oCliente.bpNombre.ToString();
            return sClienteName.ToString();

        }
        catch (System.Exception ex)
        {
            return ex.Message.ToString();
        }
    }

Result

The error I get follows:

POST http://localhost:8869/Services/WebtoolActionsDb.asmx/saveBLData 500 (Internal Server Error)    
{"Message":"Service call not valid. Parameter missing: \u0027myObject\u0027.","StackTrace":" 
en System.Web.Script.Services.WebServiceMethodData.CallMethod(Object target, IDictionary`2 parameters) 
en System.Web.Script.Services.WebServiceMethodData.CallMethodFromRawParams(Object target, IDictionary`2 parameters) 
en System.Web.Script.Services.RestHandler.InvokeMethod(HttpContext context, WebServiceMethodData methodData, IDictionary`2 rawParams)
en System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)","ExceptionType":"System.InvalidOperationException"}
share|improve this question
 
what happens if you JSON.parse(myObject)? –  MilkyWayJoe Mar 9 '12 at 20:00
 
Could you translate that error message to english please. Also in future please only use the english language on our site. Thanks. –  Kev Mar 9 '12 at 23:27

1 Answer

up vote 1 down vote accepted

There are two problems with your JavaScript. The reason you're getting a 500 error is because the JSON you're sending needs to have a "myObject" property to correspond with the parameter to saveData. You also need to change "Agent1" to "oCliente", "Agent2" to "oCliente2", and "Locations" to "oLocations" in order to match the properties in oGet.

myObject.oCliente = oNewObject;
myObject.oCliente2 = oNewObject2;
myObject.oLocations = myLocation;

$.ajax({
    // ...
    data: JSON.stringify({ myObject: myObject }),
    // ...
});

En español (traducción automática de Google):

Hay dos problemas con su JavaScript. La razón de que está recibiendo un error 500 es porque el que va a enviar JSON necesidades de tener un "MyObject" la propiedad que se correspondan con el parámetro a saveData. También es necesario cambiar "Agent1" a "oCliente", "Agent2" a "oCliente2", y "Locations" a "oLocations" con el fin de igualar las propiedades en oGet.

share|improve this answer
 
This Works!!! =) Thanks! –  KapitanX Mar 12 '12 at 13:24

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.