简体   繁体   English

如何在没有表格的情况下发出帖子请求并且不会出现错误 400

[英]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());
        }
    }
  • On the console, the url is correct在控制台上,url是正确的
  • I tried changing the type from POST to DELETE in ajax part, and HttpPost to HttpDelete - Didn't work我尝试在 ajax 部分将类型从 POST 更改为 DELETE,并将 HttpPost 更改为 HttpDelete - 没有用
  • I used the very same controller code successfully with a form that looks like that :我成功地使用了完全相同的控制器代码,表格如下所示:
<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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM