How to pass complex class as argument to httpget How to pass complex class as argument to httpget ajax ajax

How to pass complex class as argument to httpget


Your code is actually working (almost) fine. You only have a typo in this line:

data: { name: item.Name, isComplete: item.IsComplete, Id: Item.Id },

should be lowercase 'item' instead of 'Item':

data: { name: item.Name, isComplete: item.IsComplete, Id: item.Id },

Check your console in the browser, you'll see that it cannot find the object 'Item'.


HTTP Get are meant to be stateless and immutable. You cannot pass something in the request body using HTTP Get.

So you can either send query / route parameters.

I suggest to refactor your code to this:

Javascript:

function pickNFirstElements() {    const item = {        Name: "dope",        IsComplete: false,        Id: 2    };    const queryParams = new URLSearchParams(item).toString();    $.ajax({        type: "GET",        url: `${uri}/search?${queryParams}`,        cache: false,        success: function (return1) {            alert(return1.name);        }    })};

C#:

[HttpGet("search")]public async Task<ActionResult<TodoItem>> GetMatchingTodoItem(string name, bool isComplete, int Id){    return await _context.TodoItems.FirstAsync();}