【问题标题】:Post default BindProperty data to Razor Page using JQuery ajax使用 JQuery ajax 将默认 BindProperty 数据发布到 Razor 页面
【发布时间】:2019-02-18 21:30:27
【问题描述】:

我正在尝试使用 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/

【问题讨论】:

    标签: jquery asp.net-core-2.1 razor-pages


    【解决方案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);
        }
    });
    

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

    【讨论】:

    • 这个值是空的。
    • 您能否编辑您的问题以包含表单的 HTML?
    • @Ramesh 根据您发布的小提琴更新了我的答案。
    猜你喜欢
    • 2020-04-25
    • 1970-01-01
    • 2021-01-26
    • 2023-03-24
    • 1970-01-01
    • 2012-10-23
    • 2021-07-01
    • 1970-01-01
    • 2011-05-13
    相关资源
    最近更新 更多