I have an ASP.NET Core web application. Some of my calls such as deleting I prefer doing with a pure ajax request rather than using an actual MVC form and postback. My controller has both actions that return views and additionally actions like the delete method below that act more like an API.
With the below core I am getting into the action successfully, but the id param is always null. What am I doing wrong?
MVC Controller:
// POST: Users/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Delete([FromBody] string id)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var user = await _userManager.FindByIdAsync(id);
if (user == null)
{
return NotFound();
}
await _userManager.DeleteAsync(user);
return Ok(user);
}
AJAX Request:
$.ajax({
url: '@Url.Action("Delete", "Projects")',
contentType: "application/json",
type: "POST",
headers:
{
"RequestVerificationToken": '@GetAntiXsrfRequestToken()'
},
data: JSON.stringify({ "id": "ABC123" }),
success: function () {
alert('Deleted Successfully');
// Remove row from grid.
}
});
Is it common to have to create both actions that return views and actions that act more like API calls for AJAX Requests in an ASP.NET MVC Web app? I am not considering it an API call because I still want to pass the AntiForgeryToken.
nullif you make a post request using for example Postman? Just trying to verify ifURL.Action()generates the correct URL.