jQuery AJAX 将字符串发布到 MVC 控制器空参数

问题描述

我正在尝试进行一个非常简单的 AJAX 调用,它是一个搜索字符串,它会将一个值作为搜索字符串发送到控制器。

$.ajax({
    url: '/ResultsProcessing/AthleteLookup/n',type: 'POST',data: searchstring,processData: false,contentType: "application/x-www-form-urlencoded",dataType: 'html',success: function (response) {
         console.log(response);
         if (response) {  // check if data is defined
             //Do something
         }
    }
});

但是,无论我尝试和配置什么,我的控制器都不会收到字符串参数

[HttpPost]
public async Task<IActionResult> AthleteLookup(string searchstring)

这可能是非常愚蠢的事情。但是如何将搜索参数传递给我的控制器

解决方法

尝试修改您的代码如下:

        $.ajax({ 
            url: '/ResultsProcessing/AthleteLookup',type: 'POST',data: { "searchstring": $("#txtSearch").val() },//get the search string
            success: function (response) {
                console.log(response);
                if (response) {  // check if data is defined
                    //Do something
                }
            }
        });

或者您可以在请求 url 的末尾附加搜索字符串,代码如下:

[注意] 使用此方法,无需将ajax方法设置为Post,并在控制器中使用[HttpPost]属性,我们可以使用Get方法。

        $.ajax({
            url: '/ResultsProcessing/AthleteLookup/?searchstring=' + $("#txtSearch").val(),success: function (response) {
                console.log(response);
                if (response) {  // check if data is defined
                    //Do something
                }
            }
        });

控制器代码如下:

    [HttpPost]
    public async Task<IActionResult> AthleteLookup(string searchstring)
    {
        return new JsonResult("Search string: " + searchstring);
    }

测试结果如下:

enter image description here