Post 使用 JQuery ajax 默认 BindProperty 数据到 Razor 页面

Post default BindProperty data to Razor Page using JQuery ajax

我正在尝试 post 使用 ajax 请求 Asp.Net Core 2.1 Razor 页面的数据。

$.ajax({
    type: "POST",
    url: "/MyPage",
    data: { "Key1": Val1},
    beforeSend: function (xhr) {
        xhr.setRequestHeader("XSRF-TOKEN",
            $('input:hidden[name="__RequestVerificationToken"]').val());
    },
    contentType: false,
    processData: false,
    success: function (response) {
        if (response == "Success")
            alert("Successfully saved.");
        else {
            alert(response);
        }
    },
    error: function (e) {
        alert(e.responseText);
    }
});

这里一切正常。

现在,我想传递大约 50 个文本框的值,所以不使用 data: { "Key1": Val1}, 有没有其他方法可以绑定 [BindProperty] class

我的 PageModel 看起来

[BindProperty]
public InputModel Input { get; set; }

有关 .cshtml 的更多信息

https://jsfiddle.net/4sb8vqda/1/

您可以使用 serialize method:

$.ajax({
    type: "POST",
    url: "/MyPage",
    headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
    data: $('#theFormId').serialize(),
    success: function (response) {
        if (response == "Success")
            alert("Successfully saved.");
        else {
            alert(response);
        }
    },
    error: function (e) {
        alert(e.responseText);
    }
});

您设置了错误的 header 值。另外,不要将 contenttype 设置为 false。这导致 contenttype 被设置为 text/plain 而不是 application/x-www-form-urlencoded; charset=UTF-8 ,您需要将其设置为传输表单值。