英文:
error 400 when try to make ajax request with type post to function OnPostshiftDataUp
问题
I am working with Asp.Net Core Razor Pages. I get an error when trying to make an ajax request to access OnPostshiftDataUp
.
ERROR: Failed to load resource: the server responded with a status of 400 ()
console.log(formdata) // serialize data
serverip=172.16.224.999&printername=Zebra2&Location=SupervisorOffice&__RequestVerificationToken=CfDJ8DvYZnvxyLVKi-zvp3jzTImPtgQsnvTBz4ot8mbln2lEaqGcaT_gzZ-KNNfuEBoqHYSBIdcahXL3LLuum4nfTi2oZDQj-PfodyDAVpa45rYEIb7EcRvHrMn71AyB8PMC6DrqvT8q3cCEcSlt1sYQJ-M
but the breakpoint does not catch this function, meaning it does not detect that there are breakpoints that must catch it.
The main purpose of the ajax request is to save data after updating data on the Bootstrap modal.
What I tried for my code:
- Function with type post on the page model:
public ActionResult OnPostshiftDataUp()
{
return Content("msg");
}
- Ajax request to access function or action
OnPostshiftDataUp
:
$('#save-btn').click(function () {
var formData = $('#edit-form').serialize();
console.log(formData);
$.ajax({
url: '?handler=shiftDataUp',
type: "POST",
data: JSON.stringify(formData),
success: function (result) {
$('#edit-modal').modal('hide');
location.reload();
},
error: function (xhr, status, error) {
console.log(error);
}
});
});
Bootstrap modal then sends an ajax request when clicking the "Save" button:
<div class="modal fade" id="editshelflabelModal" tabindex="-1" role="dialog" aria-labelledby="userDetailsModalLabel" aria-hidden="true">
<!-- ... (modal content) ... -->
</div>
<table id="editbootstarp">
<!-- ... (table content) ... -->
</table>
$(document).ready(function(){
// ... (click event handler and ajax request) ...
});
If you continue to experience issues, please provide more specific information about the problem so that I can assist you further.
英文:
I am working with Asp.Net Core Razor Pages. I get an error when trying make ajax request to access OnPostshiftDataUp
ERROR : Failed to load resource: the server responded with a status of 400 ()
console.log(formdata) // serialize data
serverip=172.16.224.999&printername=Zebra2&Location=SupervisorOffice&__RequestVerificationToken=CfDJ8DvYZnvxyLVKi-zvp3jzTImPtgQsnvTBz4ot8mbln2lEaqGcaT_gzZ-KNNfuEBoqHYSBIdcahXL3LLuum4nfTi2oZDQj-PfodyDAVpa45rYEIb7EcRvHrMn71AyB8PMC6DrqvT8q3cCEcSlt1sYQJ-M
but break point not catch this function meaning not detect there are breakpoint must catch it
the main purpose from ajax request is save data after update data on bootstrap model
what I try for my code
1- function with type post on page model
public ActionResult OnPostshiftDataUp()
{
return Content("msg");
}
2- ajax request to access function or action OnPostshiftDataUp
ajax request i do it
$('#save-btn').click(function () {
var formData = $('#edit-form').serialize();
console.log(formData);
$.ajax({
url: '?handler=shiftDataUp',
type: "POST",
data: JSON.stringify(formData),
success: function (result) {
$('#edit-modal').modal('hide');
location.reload();
},
error: function (xhr, status, error) {
console.log(error);
}
});
});
bootstrap model then send ajax request when click button save
<div class="modal fade" id="editshelflabelModal" tabindex="-1" role="dialog" aria-labelledby="userDetailsModalLabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<h5 class="modal-title" style="text-align:center;">
@*<img src="@Url.Content("~/Img/UserProfile1.png")" alt="ImageProfile" style="width:22%;height:10%" />*@
</h5>
<div class="modal-header">
<h5 class="modal-title" id="editshelflabelModaldata" style="margin-left:200px;">Hi,@TempData["UserID"]</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="modal-body">
<form id="edit-form" method="post">
@* <input type="hidden" id="edit-id" name="ShiftId">*@
<div class="form-group">
<label for="edit-server">Server IP</label>
<input type="text" class="form-control" id="edit-ip" name="serverip">
</div>
<div class="form-group">
<label for="edit-printer">Printer Name</label>
<input type="text" class="form-control" id="edit-printername" name="printername">
</div>
<div class="form-group">
<label for="edit-locationsdata">Location Name</label>
<input type="text" class="form-control" id="edit-Location" value="save" name="Location">
</div>
</form>
@*<div class="form-group row">
<label for="serverIp" class="col-sm-1 col-form-label" style="font-size:15px;font-family: 'Open Sans', sans-serif;font-weight: bold;">Server IP</label>
<div class="col-sm-3">
<input id="serverIp" asp-for="User.UserName" readonly type="text" class="form-control" style=" margin-left:10px;font-size:15px;font-family: 'Open Sans' , sans-serif;font-weight: bold;" maxlength="30" />
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary" id="save-btn">Save changes</button>
</div>
</div>
</div>
</div>
updated post
issue still exist after apply answer below :
error display Failed to load resource: the server responded with a status of 400 ()
so what i do to solve error
Last updated Post
issue until now not solved can you please help me by sending full sample with bootstrap model and jQuery and html table may be i have issue on some parts please
From code below request success done but function post PostshiftDataUp()
not cached or hit after click save button
Full code sample for what I try
program.cs
builder.Services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");
public class ShelfLabelPrinterSetUpModel : PageModel
{
[BindProperty]
public string serverip { get; set; }
[BindProperty]
public string printername { get; set; }
[BindProperty]
public string Location { get; set; }
public IActionResult OnPostshiftDataUp(string serverip, string printername, string location)
{
return new JsonResult("Success");
}
}
<div class="modal fade" id="editshelflabelModal" tabindex="-1" role="dialog" aria-labelledby="userDetailsModalLabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<h5 class="modal-title" style="text-align:center;">
</h5>
<div class="modal-header">
<h5 class="modal-title" id="editshelflabelModaldata" style="margin-left:200px;">Hi,@TempData["UserID"]</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="modal-body">
<form id="edit-form" method="post">
<div class="form-group">
<label for="edit-server">Server IP</label>
<input type="text" class="form-control" id="edit-ip" name="serverip">
</div>
<div class="form-group">
<label for="edit-printer">Printer Name</label>
<input type="text" class="form-control" id="edit-printername" name="printername">
</div>
<div class="form-group">
<label for="edit-locationsdata">Location Name</label>
<input type="text" class="form-control" id="edit-Location" name="Location">
</div>
<button type="button" class="btn btn-primary" id="save-btn">Save changes</button>
</form>
<a href="/"><i class="fas fa-sign-out-alt"></i> Sign Out</a>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<table id="editbootstarp">
<thead>
<tr>
<th style="display:none;">ID</th>
<th>BranchType</th>
<th>UserPC</th>
<th>PrinterName</th>
<th>ArabicConfig</th>
<th>Status</th>
<th>Location Name</th>
<th>>Action</th>
</tr>
</thead>
<tbody>
@foreach (DataRow row in table.Rows)
{
<tr>
<td style="display:none;">@row["AutoID"]</td>
<td>@row["BranchType"]</td>
<td>@row["UserPC"]</td>
<td>@row["PrinterName"]</td>
<td>@row["ArabicConfig"]</td>
<td>@row["Status"]</td>
<td>@row["DisplayName"]</td>
<td>
<button class="editbt" data.Location="@row["DisplayName"]" data.printername="@row["PrinterName"]" data.serverip="@row["UserPC"]">Edit</button>
</td>
</tr>
}
</tbody>
</table>
@section scripts {
<script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-1.8.0.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.22/jquery-ui.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#editbootstarp tbody').on('click', 'tr', function () {
// Get the data from the clicked row
var rowData = $(this).children('td').map(function () {
return $(this).text();
}).get();
$('#editshelflabelModal #edit-ip').val(rowData[2]);
$('#editshelflabelModal #edit-printername').val(rowData[3]);
$('#editshelflabelModal #edit-Location').val(rowData[6]);
$('#editshelflabelModal').modal('show');
});
$('#save-btn').click(function () {
var formData = $('#edit-form').serialize();
console.log(formData);
$.ajax({
url: '?handler=shiftDataUp',
type: "POST",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data:formData,
success: function (result) {
alert(result);
},
error: function (xhr, status, error) {
console.log(error);
}
});
});
});
});
network tool browser gool chrome result also
Request URL:
https://localhost:7160/ShelfLabelPrinterSetUp?handler=shiftDataUp
Request Method:
POST
Status Code:
200
Remote Address:
[::1]:7160
Referrer Policy:
strict-origin-when-cross-origin
答案1
得分: 1
您之所以收到400 Bad Request错误是因为您未通过Razor Pages默认内置的反请求伪造检查。有关详细信息,请参阅:https://www.learnrazorpages.com/security/request-verification
当您将表单数据转换为JSON时,请求验证令牌将隐藏在请求体中,作为JSON负载的一部分。在这种情况下,Razor Pages无法读取令牌,因此您需要将请求验证令牌发送到标头中:
$.ajax({
url: '?handler=shiftDataUp',
type: "POST",
contentType: "application/json",
headers: {
"RequestVerificationToken": $('[name="__RequestVerificationToken"]').val()
},
data: JSON.stringify(formData)
...
或者,不要将表单序列化为JSON。将其原样发送:
$.ajax({
url: '?handler=shiftDataUp',
type: "POST",
data: $('#edit-form').serialize()
...
英文:
You are getting a 400 Bad Request because you are failing the anti-request forgery check which is built into Razor Pages by default: https://www.learnrazorpages.com/security/request-verification
When you convert the form data to JSON, the request verification token is hidden in the request body as part of the JSON payload. Razor Pages is unable to read the token in that condition, so you need to send the request verification token in the headers:
$.ajax({
url: '?handler=shiftDataUp',
type: "POST",
contentType: "application/json",
headers: {
"RequestVerificationToken" : $('[name="__RequestVerificationToken"]').val()
},
data: JSON.stringify(formData)
...
Alternatively, don't serialise the form to JSON. Send it as-is:
$.ajax({
url: '?handler=shiftDataUp',
type: "POST",
data: $('#edit-form').serialize()
...
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论