[英]How to make a post request without form and without getting error 400
I'm sending a post request without a form in asp.net.我在asp.net 中发送了一个没有表单的post 请求。 I'm getting error 400.
我收到错误 400。
AJAX AJAX
function deteleCategorieBtn(id) {
if (confirm("Are you sure you want to delete ?")) {
$.ajax({
type: "POST",
url: 'categories/delete/' + id,
success: function () {
var dataTable = $('#kt_datatable').DataTable();
dataTable.ajax.reload(null, false);
},
error: function (request, error) {
console.log(request, error);
}
})
}
CONTROLLER控制器
// POST: Categories/Delete/5
[Route("delete/{id?}")]
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Delete(int id)
{
var category = await _context.Categories
.FirstOrDefaultAsync(m => m.Id == id);
if(category != null){
_context.Categories.Remove(category);
await _context.SaveChangesAsync();
}
else
{
return Json(new { error = true, messages = "Categorie doesn't exist" }, new Newtonsoft.Json.JsonSerializerSettings());
}
return Json(new { success = true, messages = "Registered well" }, new Newtonsoft.Json.JsonSerializerSettings());
}
}
<form asp-action="Delete" asp-route-id="@item.Id" onclick="return confirm('Are you sure you want to delete ? ?');">
<button type="submit" value="Delete" class="btn btn-sm btn-clean btn-icon"></button>
</form>
EDIT : Found this error message :编辑:发现此错误消息:
System.InvalidOperationException: The provider for the source IQueryable doesn't implement IDbAsyncQueryProvider. Only providers that implement IDbAsyncQueryProvider can be used for Entity Framework asynchronous operations.
You need to add an Antiforgery token while doing the ajax post.您需要在执行 ajax 帖子时添加 Antiforgery 令牌。
Add an antiforgerytoken like below in your page在您的页面中添加如下所示的防伪令牌
@Html.AntiForgeryToken()
This will be added in a hidden input field这将添加到隐藏的输入字段中
While doing the ajax post, send the token like below在执行 ajax post 时,发送如下所示的令牌
$.ajax({
type: "POST",
url: 'categories/delete/' + id,
beforeSend: function (xhr) {
xhr.setRequestHeader('XSRF-TOKEN',
$('input:hidden[name="__RequestVerificationToken"]').val());
},
success: function () {
var dataTable = $('#kt_datatable').DataTable();
dataTable.ajax.reload(null, false);
},
error: function (request, error) {
console.log(request, error);
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.