2

I have this controller that takes a List of type ApplicationsListViewModel. However, my ajax function seems to be sending nothing to it even though I have checked it in the console.

Controller

[HttpPost]
public ActionResult Delete(List<ApplicationsListViewModel> Input)
{
    foreach (var item in Input)
    {
        applicationsData.Delete(item.Id);
    }
    return Ok();
}

ViewModel

public class ApplicationsListViewModel
{
    public string Id { get; set; }
    public string Name { get; set; }
    public string SecretKey { get; set; }
    [DataType(DataType.DateTime)]
    [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd HH:ii:ss}", ApplyFormatInEditMode = true)]
    public DateTime CreatedOn { get; set; }
}

Ajax function

$(".subnavigation-list").on("click", "#delete", function (e) {
    selected = table.rows('.selected').data().toArray();
    var form_data = selected;
    $.ajax({
        url: "@Url.Action("Delete", @ViewContext.RouteData.Values["controller"].ToString())",
        method: "POST",
        data: JSON.stringify(form_data),
        contentType: "application/json",
        success: function (result) {
            $.each(selected, function (index, value) {
                toastr.success("Deleted "+value.Name);
            });
            table.draw();
        },
        error: function (error) {
            console.log(error);
        }
    });
    return false;
});

When I logged the form_data that is being sent across, I get this:

[{…}]
0: {Id: "a2306cd6-c260-40f0-a51e-f76142206d91", Name: "Application One", SecretKey: "mN9D626lqYqIJdlhI44482/XCSUuiz5IQBEezAmOHoA=", CreatedOn: "2018-10-01T00:19:39.1165394"}
length: 1
__proto__: Array(0)

Am I missing something? It used to work in .NET MVC 5.

5
  • can you confirm that the Delete action is getting called? I think something might be wrong with the url in your AJAX call, I usually define it like /AppFolder/Contoller/Delete Commented Sep 30, 2018 at 16:10
  • 1
    Possible duplicate of Asp.net Core 2 API POST Objects are NULL? Commented Sep 30, 2018 at 16:15
  • I can confirm that the delete action is called because I've set a debugger there Commented Sep 30, 2018 at 16:36
  • @KirkLarkin its not an api post. Commented Sep 30, 2018 at 16:42
  • Try passing in a single view model that contains an array instead of vice versa, I believe that's the convention. You shouldn't have to use [FromBody] Commented Sep 30, 2018 at 18:01

1 Answer 1

0

In post action at parameters you must include [FromBody] attribute just like this:

[HttpPost]
public ActionResult Delete([FromBody] List<ApplicationsListViewModel> Input)
Sign up to request clarification or add additional context in comments.

Comments

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.