Home > Mobile >  unpacking json in Ajax
unpacking json in Ajax

Time:06-08

while unpacking json in Ajax I ran into an error

Uncaught TypeError: Cannot read properties of undefined (reading 'GrossSalesPriceForUser')

in controller i have class, i create object and i sent values to new object i want to sent it to view now

Controller

 public class CalsEarlyStatementForUser
  {
    public decimal GrossSalesPriceForUser { get; set; }
    public decimal PaidBeneficiaryForUser { get; set; }
  }

//(...)
//method
      CalsEarlyStatementForUser objCalsEarlyStatementForUser = new CalsEarlyStatementForUser();
      objCalsEarlyStatementForUser.GrossSalesPriceForUser = grossSalesPriceForUser;
      objCalsEarlyStatementForUser.PaidBeneficiaryForUser = paidBeneficiaryForUser;

      var jsonData = JsonConvert.SerializeObject(objCalsEarlyStatementForUser);

      return Json(jsonData);
}

View

$.ajax({

            url: "@Url.Action("CalcEarlyStatement", "Calculations")",
            type: "GET",
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            data: {"data": JSON.stringify(data)},
            cache: false,
            success: function (result) {
            
                    // it dont work
                $("#GrossSalesPriceForUser")
                    .dxNumberBox("instance")
                    .option("value", result.objCalsEarlyStatementForUser.GrossSalesPriceForUser);                    
                $("#PaidBeneficiaryForUser")
                    .dxNumberBox("instance")
                    .option("value", result.objCalsEarlyStatementForUser.PaidBeneficiaryForUser);

                               

            },
            failure: function (error) {
                alert(error);

            },
            error: function (error) {
                alert(error);
            }
        });

CodePudding user response:

These lines are redundant:

var jsonData = JsonConvert.SerializeObject(objCalsEarlyStatementForUser);

return Json(jsonData);

As a result, you're not returning an object, but merely a JSON string. So the result variable in your client-side code is just a string and has no objCalsEarlyStatementForUser property. You'd have to deserialize the string client-side to get the object.

Instead, just return the object itself:

return Json(objCalsEarlyStatementForUser);

The server-side framework will handle serializing it over the wire for you, and the client-side framework will handle deserializing it from the response for you. Otherwise, if you double-serialize it on the server, you'd need to double-deserialize it on the client.

  • Related