【问题标题】:Asp.Net core MVC Javascript Ajax parameters null HttpPostAsp.Net core MVC Javascript Ajax 参数 null HttpPost
【发布时间】:2020-09-27 04:37:02
【问题描述】:

我正在为一个按钮编写一个 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>

它正确导航到我的代理控制器中的函数 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;
        }

如果有人能指出我哪里出错了,那将是非常有帮助的。

【问题讨论】:

  • 你能发布你的控制器代码吗?
  • @NemanjaTodorovic 我已将控制器代码添加到问题中!请看一下

标签: javascript ajax asp.net-core asp.net-core-mvc http-post


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2020-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多