1

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.

1
  • Is the param still null if you make a post request using for example Postman? Just trying to verify if URL.Action() generates the correct URL. Commented Nov 2, 2017 at 19:51

1 Answer 1

1

You send a json object { "id": "ABC123" } and so your action method should expect some simple class with id property:

public class Dto
{
   public int Id {get; set;}
}

and

public async Task<IActionResult> Delete([FromBody] Dto data)
Sign up to request clarification or add additional context in comments.

4 Comments

Makes sense, but what would you recommend I do if the controller just wants a simple Id as a param. Should I switch the action method to be of type DELETE and send the id in the URL?
@BlakeRivell actually yes, if you free to use another endpoint, and you want to follow the REST pattern, then the HTTP Delete method with id as part of URL is the most suitable option.
I am aware this might be a preference based question, but does it make sense to have action methods like that in an ASP.NET MVC app for when I am making pure AJAX calls and do not need a view returned? Would you recommend making an API folder for anything that doesn't return a view?
@BlakeRivell: ASP.NET Core doesn't do MVC/WebAPI separation like it was in old ASP.NET. It has one MVC middleware that covers all this, and from any controller you can return a View or object data.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.