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.

JianYA
  • 2,750
  • 8
  • 60
  • 136
  • 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 – user287474 Sep 30 '18 at 16:10
  • 1
    Possible duplicate of [Asp.net Core 2 API POST Objects are NULL?](https://stackoverflow.com/questions/45862459/asp-net-core-2-api-post-objects-are-null) – Kirk Larkin Sep 30 '18 at 16:15
  • I can confirm that the delete action is called because I've set a debugger there – JianYA Sep 30 '18 at 16:36
  • @KirkLarkin its not an api post. – JianYA Sep 30 '18 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] – user287474 Sep 30 '18 at 18:01

1 Answers1

0

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

[HttpPost]
public ActionResult Delete([FromBody] List<ApplicationsListViewModel> Input)