简体   繁体   中英

ASP.NET Core 2.1 passing json list to ajax

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM