Answer the question
In order to leave comments, you need to log in
How to pass data to the controller??
Created an API controller that fails to pass data to:
[Route("api/User")]
[ApiController]
public class UserApiController : ControllerBase
{
[HttpPost("data")]
public async Task<JsonResult> data(string dataOld, string dataNew)
{
return null;
}
[HttpPost("Settings")]
public async Task<JsonResult> Settings([FromBody] JObject jObject)
{
return null;
}
$.post(
"/api/User/data",
{
dataOld: "param1",
dataNew: "param2"
},
function (data) {
alert(JSON.stringify(data));
}
);
var books = [{
name: "Чайка",
price: 200,
}, {
name: "Война и мир",
price: 230,
}];
$.ajax({
url: '/api/User/Settings',
type: 'POST',
data: JSON.stringify(books),
contentType: "application/json;charset=utf-8",
success: function (data) {
alert('Данные отправлены');
}
});
Answer the question
In order to leave comments, you need to log in
I think that the problem is
because in fact, with this line you are sending a string, not an object. Type mismatch, he does not see it.
If you want to accept an object in the method, you don't need to convert it to a string, you can just do it
. But something tells me that in your version there may be problems here as well. Why are you accepting a JObject?
Transform it later, accept it as an array
Better yet, type properly, and then do something like JObject.FromObject(books).
PS:
In such cases, it would be good to attach the text of the error to the question.
1. You call the Password method in the first case.
2. In the parameters of the controller methods, there must be a data model that you pass, such as
class Book
{
public string Name {get; set;}
public int Price {get; set;}
}
public async Task<IActionResult> Settings([FromBody] Book[] books)
{
return Ok()
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question