2
votes

Can anyone help me and point out where is my problem getting undefined property response? I'm calling Controller Action Method and returning Json result. I want to populate several input fields in my view, but I get undefined property.

This is my controller Action:

public IActionResult GetServicePrice(int? serviceId)
{
  var spParams = new DynamicParameters();
  spParams.Add("@ServiceId", serviceId);

  var data = _repository.SpSingle<GetServiceResult>("GetServices", spParams);

  return Json(new { data });
}

My JavaScript code for testing is:

function GetServicePrice(serviceId) {
    const url = "/admin/Sale/GetServicePrice";

    $.ajax({
        url: url,
        type: "POST",
        dataType: "json",
        data: {
            serviceId: serviceId
        },
        success: function (data) {
            alert(data.serviceId);
            alert(data.price);
            //$("#ServicePrice").val(data.price);
        },
        error: function (request, status, error) {
            alert(request.responseText);
        }

    });

This is the Response:

{"data":{"serviceId":4,"price":6400.0000}}

Thank You!

so you'd access those values like data.data.serviceId and data.data.price - if that's confusing to you ... change to success: function (result) { ... now you would use result.data.price for example - Jaromanda X
@JaromandaX thank you for your answer, it's not confusing but frustrating :) Thank's again. - Verica Jovanova
the fact that your function argument is called data and that the returned object has a data element can be confusing ... I forgot to mention you could've also done success: function ({data}) { ... and then your alerts would work ... now are you confused :p - Jaromanda X