admin管理员组

文章数量:1406926

When I using jquery Ajax POST method to controller like:

var data = {
    ID: '1',
    name: 'TEST',       
 }


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

                .............
            
  })

My backend not working when use the string parameter like:

//C#
[HttpPost]
public bool ActionName(string ID, string name){

}

But it works when using object like:

//C#
[HttpPost]
public bool ActionName(object data){

}

I don't know why in this situation

When I using jquery Ajax POST method to controller like:

var data = {
    ID: '1',
    name: 'TEST',       
 }


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

                .............
            
  })

My backend not working when use the string parameter like:

//C#
[HttpPost]
public bool ActionName(string ID, string name){

}

But it works when using object like:

//C#
[HttpPost]
public bool ActionName(object data){

}

I don't know why in this situation

Share Improve this question edited Mar 6 at 11:28 ADyson 62.2k16 gold badges79 silver badges92 bronze badges asked Mar 6 at 10:09 Ansel LiouAnsel Liou 252 bronze badges 1
  • 1 Your first version will expect to receive form-url-encoded parameters in the body of the request, not a JSON object. – ADyson Commented Mar 6 at 11:27
Add a comment  | 

1 Answer 1

Reset to default 1

When an action method has definition like

[HttpPost]
public JsonResult ActionName(string id, string name)
{
    ...
    return Json(true);
}

this means that the corresponding .ajax() call should pass two different parameters to the method, but not an object encapsulating these two parameters like in the question above.

Therefore, to call the method above try to use the following code fragment:

 $.ajax({
     type: "POST",
     url: url,                
     data: { id: "1", name: "TEST" },
     /* contentType: 'application/json; charset=utf-8', */    
     dataType: "json",
     success: function (result, status, xhr) { },
     error: function (xhr, status, error) { }
});

I omitted the contentType parameter and used the default value application/x-www-form-urlencoded; charset=UTF-8, because of parameters are bound using the request headers.

本文标签: jqueryWhen AJAX POST to C httpPost medthod hasProblemStack Overflow