问题通常出现在将数据从前端传递到后端时,如果需要将数据值绑定到控制器的参数中,可以使用以下方法:
$.ajax({
url: "/api/ControllerName/ActionName",
type: "POST",
dataType: "json",
contentType: "application/json",
data: JSON.stringify({ id: 1, name: "test" }),
success: function (response) {
console.log(response);
},
error: function (error) {
console.log(error);
}
});
[HttpPost]
public IActionResult ActionName([FromForm] int id, [FromForm] string name)
{
// Do something with id and name
return Ok();
}
这样,在控制器中就可以正确地获取来自前端的数据值,并将其用于进一步的操作。