Home > Back-end >  why POST request method returns null but GET request returns correct object
why POST request method returns null but GET request returns correct object

Time:07-18

This is my controller code :

[HttpPost]
public async Task<JsonResult> GetWebsite(int Id)
{
    var website = await _uWebsitesService.GetWebsite(Id);
    return (website == null ? this.Json("Website Not Found") : this.Json(website));
}

And this is my ajax :

$(".edit-website-btn").on("click", function () {

let id = $(this).attr('data-id');

$.ajax({
    type: "POST",
    url: "/userpanel/GetWebsite/",
    data: { Id: id },
    dataType: "json",
    contentType: "application/json",
    success: function (result) {
        console.log(result);
    },
    error: function (error) {
        console.log(error);
    },
  })
})

When I check the result in console log, it's null when request type is post but when I change The ajax request and controller method to GET it returns the correct object.

CodePudding user response:

this is because for your post method you are using application/json content that doesnt send id to an action, so action is using id=0 by default and can't get any data. Get action has a correct id and returns data. you can try to fix ajax for post by removing contentType: "application/json"

$.ajax({
    type: "POST",
    url: "/userpanel/GetWebsite/",
    data: { Id: id },
    dataType: "json",
    .....

but imho better to use GET

$.ajax({
    type: "GET",
    url: "/userpanel/GetWebsite?id=" id,
   dataType: "json",
    ...

and maybe you should try this too

 let Id = $(this).data('id');
 //or
 let Id = this.getAttribute('data-id');

CodePudding user response:

Your data parameter in the ajax call is an object, which just so happens to have a property called Id with the value you want.

However, your C# method expects just an integer, not an object with a property called "Id".

Simply change the JavaScript to only post the integer.

data: id,

To also help out C#'s binding, you should also specify that the parameter is from the request's body. This is techinally optional, but might help with maintainability and ensuring your value doesn't accidently come in from another source (like a rouge query param).

public async Task<JsonResult> GetWebsite([FromBody] int Id)

If you need to pass more than one value in the POST call, you'll need to make a class in C# and bind that instead of the int.

  • Related