为什么模型绑定不起作用? ASP.NET 核心 5.0 RazorPages

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

ASP.NET 核心 5.0 剃刀页面。

发布数组时,模型未绑定 - 值显示为空数组。

这是使用 Ajax -

发布的 JSON 数组
[
    { "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 操作方法

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

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

POST 的 data 参数应该是对象值,而不是它的字符串化版本。尝试更改为:

...
data: newOrderDictionary,
...

假设 newOrderDictionary 是一个数组。

事实证明这是可行的:

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


function UpdateImageOrder() {

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

    success: function (response) {

    }
});

}

考虑使用post传递数据,需要在ajax中加入contentType:"application/json"

$.ajax({
            type: "POST",
            url: "/?handler",
            dataType: "json",

            contentType:"application/json",
            //...
        });

此外,在bakend中添加[FromBody]

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

    }

然后,就可以拿到数据了。