Ad

Asp.Net Core MVC Javascript Ajax Parameters Null HttpPost

I am writing a javascript function for a button

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

This is what my javascript function looks like

<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>

It correctly navigates to the function StopTest in my Agents controller but the parameters passed to it are null.

My controller code is

[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;
        }

It would be of great help if anyone could point out where I am going wrong.

Ad

Answer

You should create a class with two properties:

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

And then in your controller you should have action signature like this:

public bool StopTest([FromBody]Test data)

You can see more about model binding in asp.net core here: https://docs.microsoft.com/en-us/aspnet/core/mvc/models/model-binding?view=aspnetcore-3.1

Ad
source: stackoverflow.com
Ad