Search code examples
asp.net-corerazor-pages

Why is the model binding not working? ASP.NET Core 5.0 RazorPages


ASP.NET Core 5.0 Razor Pages.

When posting the array, the model is not binding - value is showing empty array.

This is a JSON array posted using Ajax -

[
    { "Order":1, "FileName":"bbed5ecf-4133-4681-b0f3-c11366ad3186.jpg" },
    { "Order":2, "FileName":"737e60dc-0631-493d-947d-2f5948d7818c.jpg" },
    { "Order":3, "FileName":"6c76f9d1-44bd-4b80-926e-2ce4307eb30b.jpg"}
]

function UpdateImageOrder() {

$.ajax({
    type: "POST",
    url: "/property/imagesorter",
    dataType: "json",
    headers:
    {
        "RequestVerificationToken": $('input:hidden[name="__RequestVerificationToken"]').val()
    },
    data: JSON.stringify(newOrderDictionary),
    success: function (response) {

    }
});

}

RazorPage action Method

 public async Task OnPostAsync(ImageOrder[] data)
 {
 }

 public class ImageOrder
 {
    public int Order { get; set; }
    public string FileName { get; set; }
 }

Solution

  • The data parameter of the POST should be the object value, not a stringified version of it. Try changing to:

    ...
    data: newOrderDictionary,
    ...
    

    Assuming newOrderDictionary is an array.