Asp.Net 核心 MVC Javascript Ajax 参数空 HttpPost

Asp.Net core MVC Javascript Ajax parameters null HttpPost

我正在为按钮编写 javascript 函数

<button type="button" class="btn btn-sm btn-outline-secondary" id="stopProcess"  onclick="stopProcess(event, @queue.AgentQueueId, @queue.AgentId)" data-toggle="tooltip">Stop</button>

这就是我的 javascript 函数的样子

<script type="text/javascript">
    $(document).ready(function () {
        setInterval(function () {
            reloadPage()
        }, 50000);
    });
    function reloadPage() {
        window.location.reload(true);
    }
    function stopProcess(e, agentQueueId, agentId) {
        e.stopPropagation();

        var data = JSON.stringify({ 'agentQueueId': agentQueueId, 'agentId': agentId });

        $.ajax({
            type: "POST",
            url: "@Url.Action("StopTest", "Agents")",
            data: data,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
                reloadPage();
            },
            error: function (data) {
                $(".alert").text("Error completing the request.");
                $(".alert").prop("hidden", false);
            }
        });
    };
</script>

它正确导航到我的 Agents 控制器中的 StopTest 函数,但传递给它的参数为空。

我的控制器代码是

[HttpPost]
        public bool StopTest(long agentQueueId, long agentId)
        {
            StopTestsResponse response = new StopTestsResponse();
            try
            {
                response = _testAgentRepository.StopTest(new StopTestsRequest()
                {
                    AgentId = agentId,
                    AgentQueueId = agentQueueId
                });
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return response.Success;
        }

如果有人能指出我哪里出错了,那将很有帮助。

您应该创建一个具有两个属性的 class:

public class Test 
{
   public long AgentQueueId { get; set; }
   public long AgentId { get; set; }
}

然后在你的控制器中你应该有这样的动作签名:

public bool StopTest([FromBody]Test data)

您可以在此处查看 asp.net 核心中有关模型绑定的更多信息: https://docs.microsoft.com/en-us/aspnet/core/mvc/models/model-binding?view=aspnetcore-3.1