简体   繁体   English

Ajax 请求:未将 Json 数据传递给控制器

[英]Ajax Request: Json Data Not Being Passed to Controller

I'm building a program that searches documents in ASP.NET Core.我正在构建一个在 ASP.NET Core 中搜索文档的程序。 I'm passing the search data from a text box to the controller through an Ajax request but the controller isn't receiving the string.我通过 Ajax 请求将搜索数据从文本框传递到控制器,但控制器没有接收到字符串。

I've tried changing how the ajaxData field is defined, adding quotations around 'search' and even turning the whole thing into a string but I can't get it to pass to the controller.我尝试更改 ajaxData 字段的定义方式,在“搜索”周围添加引号,甚至将整个内容转换为字符串,但我无法将其传递给控制器​​。

This is the code for the request:这是请求的代码:

ajaxData = {search: $("#textSearchBox").val()}

console.log(ajaxData);

$.ajax({
    type: 'POST',
    url: "@Url.Action("GetDocuments", "DocumentSearchApi")",
    data: ajaxData,
    dataType: "json",
    contentType: "application/json; charset=utf-8",
    error: function (e) {
        //Error Function
    },
    success: function (jsonData) {
        //Success Function
    },
    fail: function (data) {
        //Fail Function
    }
});

And this is the top of the Controller's GetDocuments function:这是 Controller 的 GetDocuments 函数的顶部:

[Route("GetDocuments")]
public async Task<IActionResult> GetDocuments(string search)
{

No error messages anywhere.任何地方都没有错误消息。 The Console shows an Object that contains 'search: "Test"' but when I hit the breakpoint in GetDocuments 'search' is null.控制台显示一个包含“搜索:“测试”的对象,但是当我在 GetDocuments 中找到断点时,“搜索”为空。

I think is more elegant way to use GET in this case then you should change your code to我认为在这种情况下使用 GET 的方式更优雅,那么您应该将代码更改为

var ajaxData = $("#textSearchBox").val();
url: "@Url.Action("GetDocuments", "DocumentSearchApi")"?search=ajaxData 

and remove data: ajaxData并删除数据:ajaxData

Because you want to get something from the search.因为你想从搜索中得到一些东西。 Using the post is when you want to modify the data from API使用 post 是当您想从 API 修改数据时

you need use JSON.stringify() when sending data to a web server, the data has to be a string not a object将数据发送到 Web 服务器时需要使用 JSON.stringify(),数据必须是字符串而不是对象

$.ajax({
    type: 'POST',
    url: "@Url.Action("GetDocuments", "DocumentSearchApi")",
    data: JSON.stringify(ajaxData),
    dataType: "json",
    contentType: "application/json; charset=utf-8",
    error: function (e) {
        //Error Function
    },
    success: function (jsonData) {
        //Success Function
    },
    fail: function (data) {
        //Fail Function
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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