这是索引文件代码:
public IList<Employee> Employee { get; set; }
public async Task OnGetAsync()
{
Employee = await _context.Employee.ToListAsync();
}
public JsonResult EmployeeList()
{
var data = _context.Employee.ToList();
return new JsonResult(data);
}
[HttpPost]
public JsonResult AddEmployee(Employee e)
{
var emp = new Employee()
{
Name = e.Name,
Age = e.Age,
Email = e.Email
};
_context.Employee.Add(emp);
_context.SaveChanges();
return new JsonResult("Success!!!");
}
打开模态的按钮:
<button class="btn btn-info mb-3" id="btn1">Add Employee</button>
模态:
<!-- The Modal -->
<div class="modal Add-Emp">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<h4 class="modal-title">Add Employee</h4>
<button type="button" class="btn-close" data-bs-dismiss="modal"></button>
</div>
<!-- Modal body -->
<div class="modal-body">
<form method="post">
<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" autocomplete="off"/>
</div>
<div class="form-group">
<label>Age</label>
<input type="text" placeholder="Enter Age" class="form-control" id="Age" autocomplete="off"/>
</div>
<div class="form-group">
<label>Email</label>
<input type="text" placeholder="Enter Email" class="form-control" id="Email" autocomplete="off"/>
</div>
</form>
</div>
<!-- Modal footer -->
<div class="modal-footer">
<button class="btn btn-primary" onclick="AddEmployee();">Save</button> I
<button class="btn btn-danger btn-default" data-bs-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
Js代码:
$("#btn1").click(function () {
$(".Add-Emp").modal("show")
})
function AddEmployee() { debugger
var objData = { Name: $("#Name").val(), Age: $("#Age").val(), Email: $("#Email").val() }
$.ajax({
url: "Pages/Employees/Index/AddEmployee",
type: "Post",
data: objData,
contentType: "application/xxx-www-form-url-encoded; charset=utf-8",
dataType: "json",
success: function () { alert("Data Saved"); },
error: function () { alert("Error!!!"); }
})
}
模态打开点击,但数据不会被张贴点击保存按钮,它显示警报“错误!!!”定义在 AJAX 请求失败
1条答案
按热度按时间0aydgbwb1#
1.您可能不熟悉Razor Pages,Razor Pages使用
OnGet
和OnPost
来处理Http Get和Post请求。如果您需要在当前PageModel中使用另一个Get或Post方法,则需要定义方法名称,如下所示:* * OnGet处理程序名称或OnPost**处理程序名称。2.如果您的
.cshtml.cs
文件位于:Pages/Employees/Index.cshtml.cs
,请求URL应为:/Employees/Index
。如果您在PageModel中设置了处理程序,则请求URL应为:/Employees/Index?handler=xxx
.3.对于如何在Razor Pages中使用Ajax,Razor Pages默认启用防伪令牌验证,所以需要在ajax中将此令牌添加到header中。
如果你在Razor Pages中使用表单,它会默认生成一个带有token的输入。如果没有,你需要手动添加
@Html.AntiForgeryToken()
。页面(页面/员工/索引. cshtml):
页面/员工/索引. cshtml.cs: