skip to Main Content

This topic is not duplicate with others my problem is in get method
i have this data:

var things = [
   { "name": "n1" },
   { "name": "n2" }
];

Ajax call:

$.ajax({
    url: /controller/GetList,
    data: JSON.stringify(things),
    contentType: "application/json; charset=utf-8",
    dataType: "json"
});

Server side:

public JsonResult GetList(
    List<Thing> things) => Json("OK");

public class Thing
{
    public string name { get; set; }
}

Now when i call ajax with method: “POST” and get data with [FromBody] in serverside everything is ok, but if i want to call ajax with GET method things in server side is null or empty, WHY?

I try this:

data: JSON.stringify({ things: things })
traditional: true

But it does not work

My project is in Asp.net Core 3.1

3

Answers


  1. You should avoid sending data (in the request body) for GET requests, because it could have complications. Many services, don’t expect GET requests to have a body and, thus they just ignore it.

    If it is not a lot of data you could try sending it in the query string, but I suggest just using POST

    Login or Signup to reply.
  2. Simply specify the method to GET:

    $.ajax({
        type : "GET",
        url: /controller/GetList,
        data: JSON.stringify(things),
        contentType: "application/json; charset=utf-8",
        dataType: "json"
    });
    
    Login or Signup to reply.
  3. If you indeed want to make GET HTTP request and pass data on JavaScript client, you can try to pass them through querystring, like below.

    var par = "";
    
    $.each(things, function (i,val) {
        par += "&things[" + i + "].name=" + val.name;
    });
    
    $.ajax({
        url: "/controller/GetList?" + par.substring(1, par.length),
        //data: JSON.stringify(things),
        contentType: "application/json; charset=utf-8",
        dataType: "json"
    });
    

    Action GetList

    public JsonResult GetList([FromQuery]List<Thing> things) => Json("OK");
    

    Test Result

    enter image description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search