1

I have been trying for few hours now to find out the solution of how to get a JSON object back:

This is my function in view together with everything I tried:

$(document).ready(function () {
    $(".nav-link").click(function () {
        var chairChosen = $(this).attr("data-id");
        var perfDateId = $("#perfDate").attr("id");
        var totalCost = $("#totalMoney").html();
        window.alert(perfDateId);
        $.ajax({
            url: '/Booking/ReserveSeat1/?id=' + chairChosen + '&perfDateId=' + perfDateId,
            type: 'GET',
            dataType: 'json',
            success: function (data1) {

                $("#test").append(typeof data1);
                $("#test").append(" notConverted" + data1.Number);
                $("#test").append(" notConverted" + data1["Number"]);
                var result1 = jQuery.parseJSON(data1);
                $("#test").append("Converted jquery" + result1.Number);
                $("#test").append("Converted jquery" + result1["Number"]);
                var result2 = JSON.stringify(data1);
                var object1 = data1;
                $("#test").append("get object " + object1.Number)
                $("#test").append("Converted parse" + result2.Number);
                $("#test").append("Converted parse" + result2["Number"]);
            },
            error: function (error) {
                $(that).remove();
                DisplayError(error.statusText);
            }
        });

    });

});

I want to mention data I don't want to send JSON data, I only expect to receive it.

The following code is in my controller:

[HttpGet]
    public ActionResult ReserveSeat1(int id, int perfDateId)
    {

        BookSeatResult bookSeat = new BookSeatResult()
        {
            Number = 10,
            Result = "a string"
        };

        return Json(bookSeat);
    }

also tried returning a JSON response from controller.

it's an mvc web app in asp.net core.

Not to forget to mention that when i do the call the controller responds, and it does return an object type

10
  • as i mentioned I am using asp.net core (version 2.2, I should have said), and JsonRequestBehavior has been deprecated in ASP.NET Core 1.0, if i try using it it says it does not exist in the current context Commented Feb 9, 2019 at 18:54
  • what error do you get Commented Feb 9, 2019 at 19:00
  • @mdln97 You should be able to retrieve the JSON data with POST method. Commented Feb 9, 2019 at 19:01
  • JsonRequestBehavior does not exist in the current context, that is the error; and there is no method for Json taking two objects Commented Feb 9, 2019 at 19:06
  • 1
    Try returning it as OkObjectResult ----> return Ok(Json(Enumerable.Range(0, t + id).ToArray())); Commented Feb 9, 2019 at 19:24

4 Answers 4

3

For Json object, it is case-sensitive which means data1.Number and data1.number are different.

For Asp.Net Core serialize, its default serializer is camelCase which means, the return Json(bookSeat); will return a json string like below:

{"number":10,"result":"a string"}

For this string, if you need to access number and result, you need to use number instead of Number.

Try

$("#test").append(data1.number);
$("#test").append(data1.result);

If you want to use data1.Number, you need to change the asp.net core to return PascalCase with configuration below in Startup.cs

services.AddMvc()
.AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver())
.SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
Sign up to request clarification or add additional context in comments.

1 Comment

This should be the accepted answer - who would know this? I spent an hour trying to debug this and went through two different methods of returning JSON to the browser, including using JsonResult and JObject serialize. What a pain!
1

Thanks for getting involved, after spending some time with your suggestions I managed to find a way to work around:

newObj.Add(bookSeat.Number.ToString());
        newObj.Add(bookSeat.Result);

        return Json(newObj.ToArray());

I am returning an array now and I access it in view as follows:

  $("#test").append(data1[1]);

Also, I analysed the data that is being received back, so I did the following:

$("#test").append(data1["result"]);

and now i get the expected string

Comments

1
$(document).ready(function () {
   $(".nav-link").click(function () {
    var chairChosen = $(this).attr("data-id");
    var perfDateId = $("#perfDate").attr("id");
    var totalCost = $("#totalMoney").html();
    window.alert(perfDateId);
    $.ajax({
        url: '/Booking/ReserveSeat1/?id=' + 
   chairChosen + '&perfDateId=' + perfDateId,
        type: 'GET',
        dataType: 'json',
        success: function (data1) {

            $("#test").append(typeof data1);
            $("#test").append(" notConverted" + 
   data1[0]["Number"]);
            $("#test").append(" notConverted" + 
  data1[0]["Number"]);
            var result1 = jQuery.parseJSON(data1);
            $("#test").append("Converted jquery" + 
 result1[0]["Number"];
            $("#test").append("Converted jquery" + 
result1[0]["Number"]);
            var result2 = JSON.stringify(data1);
            var object1 = data1;
            $("#test").append("get object " + 
object1[0]["Number"])
            $("#test").append("Converted parse" + 
 result2[0].["Number"]);
            $("#test").append("Converted parse" + 
 result2[0]["Number"]);
        },
        error: function (error) {
            $(that).remove();
            DisplayError(error.statusText);
        }
    });

});

The 0 in the data1[0]["Number"],result1[0]["Number"] is the Key. Indicating the row index in the array. I also added booSeat and returned as JSON Serialized array as shown below.

[HttpGet]
   public ActionResult ReserveSeat1(int id, int 
 perfDateId)
{

    BookSeatResult bookSeat = new BookSeatResult()
    {
        Number = 10,
        Result = "a string"
    };
 List<BookSeatResult> bookSeatList = new 
 List<BookSeatResult>();
    bookSeatList.Add(bookSeat);
    return 
    Json(JsonConvert.SerializeObject(bookSeatList
    .ToArray()));
}

The Pattern to retrieve Items in the json data within an ajax function is :

  $.ajax({
       ....
    success: function (data1) {
     var item1 = data1[0]["Attribute1"];
    }

1 Comment

For ASP.NET Core Application
0

Either remove the HttpGet attribute from the method or change it to HttpPost, and then do AJAX POST:

$.ajax({
  url: '/Booking/ReserveSeat1/?id=' + chairChosen + '&perfDateId=' + perfDateId,
  type: 'POST',
  dataType: 'json',
  success: function (data1) {

  }

//...

1 Comment

Try returning it as OkObjectResult ----> return Ok(Json(Enumerable.Range(0, t + id).ToArray()));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.