You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Razor Pages中使用Modal与Ajax提交数据失败问题求助

Razor Pages Ajax提交失败问题修复

核心错误点及修复方案

1. Razor Pages 处理方法命名不规范

Razor Pages通过OnGet/OnPost前缀识别请求类型,自定义Post动作需遵循OnPost[ActionName]Async命名约定,无需添加[HttpPost]特性。

修复后后台代码:

public IList<Employee> Employee { get; set; }

public async Task OnGetAsync()
{
    Employee = await _context.Employee.ToListAsync();
}

public JsonResult OnGetEmployeeList()
{
    var data = _context.Employee.ToList();
    return new JsonResult(data);
}

public async Task<JsonResult> OnPostAddEmployeeAsync(Employee e)
{
    var emp = new Employee()
    {
        Name = e.Name,
        Age = e.Age,
        Email = e.Email
    };
    _context.Employee.Add(emp);
    await _context.SaveChangesAsync();
    return new JsonResult("Success!!!");
}

2. 缺失AntiForgeryToken(CSRF验证)

Razor Pages默认启用CSRF防护,Post请求必须携带防伪造令牌,否则会被服务器拦截返回400错误。同时输入框需添加name属性,确保模型绑定能正确接收参数。

修复后Modal表单代码:

<!-- Modal body -->
<div class="modal-body">
    <form method="post">
        @Html.AntiForgeryToken()
        <div asp-validation-summary="ModelOnly" class="text-danger"></div>
        <div class="form-group">
            <label>Name</label>
            <input type="text" placeholder="Enter Name" class="form-control" id="Name" name="Name" autocomplete="off"/>
        </div>
        <div class="form-group">
            <label>Age</label>
            <input type="text" placeholder="Enter Age" class="form-control" id="Age" name="Age" autocomplete="off"/>
        </div>
        <div class="form-group">
            <label>Email</label>
            <input type="text" placeholder="Enter Email" class="form-control" id="Email" name="Email" autocomplete="off"/>
        </div>
    </form>
</div>

3. Ajax请求配置错误

  • URL路径错误:Razor Pages路由基于页面名称而非物理文件路径,正确格式为/页面路径?handler=动作名
  • ContentType无效:原代码中application/xxx-www-form-url-encoded为错误类型,需修正为标准的application/x-www-form-urlencoded
  • 未携带防伪造令牌:需在请求头中添加获取到的令牌

修复后JavaScript代码:

$("#btn1").click(function () {
    $(".Add-Emp").modal("show")
})

function AddEmployee() {
    var objData = { Name: $("#Name").val(), Age: $("#Age").val(), Email: $("#Email").val() }
    var token = $('input[name="__RequestVerificationToken"]').val();

    $.ajax({
        url: "/Employees/Index?handler=AddEmployee",
        type: "POST",
        data: objData,
        contentType: "application/x-www-form-urlencoded; charset=utf-8",
        headers: {
            "RequestVerificationToken": token
        },
        dataType: "json",
        success: function () { 
            alert("Data Saved"); 
            $(".Add-Emp").modal("hide");
        },
        error: function (xhr) { 
            console.log(xhr.responseText);
            alert("Error!!!"); 
        }
    })
}

内容的提问来源于stack exchange,提问作者Babar Hussain

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 22:55:38