I have the following api controller:
[Route("api/[controller]")]
[ApiController]
public class WeightingDefinitionsApiController : ControllerBase
{
[HttpPost]
public async Task<ActionResult<WeightingDefinition>> PostWeightingDefinition(int id)
{...
}
}
When I call the PostWeightingDefinition from the .Net code it works.
Now I want to call this code from a .cshtml file using a jquery.ajaxcall:
var apiurl = "/api/WeightingDefinitionsApi/";
var data = { id: 13 };
$.ajax({
url: apiurl,
type: 'POST',
dataType: 'json',
data:data,
success: function (d) {
alert("Saved Successfully");
},
error: function (x,y,z) {
alert("Error please try again");
}
});
If I connect this code to a button.click() event the code in the api controller is called but the id parameter is zero instead of 13.
Where am I going wrong?
CodePudding user response:
You ajax request sends the id as form data payload. This happens because you didn't specify the contentType option for the jQuery.ajax() request and the default is application/x-www-form-urlencoded; charset=UTF-8. So you have to add [FromForm] attribute to the id parameter of your action:
[HttpPost]
public async Task<ActionResult<WeightingDefinition>>
PostWeightingDefinition([FromForm]int id)
{
...
}
When you don't specify any attribute to the id parameter then [FromQuery] is inferred so you would have to pass the id as query parameter:
var apiurl = "/api/WeightingDefinitionsApi?id=13";
Check the following links:
ApiController attribute - Binding source parameter inference documentation
