Passing POST parameter from AJAX always null

Dondon510 261 Reputation points
2024-12-11T03:16:31.8866667+00:00

Hi All,

I do POST from ajax, but why the value always null?

AJAX:

const msg = document.getElementById("fieldWorkerNote").value;
const fieldWorker = document.getElementById("fieldWorker").value;
const recipient = document.getElementById("fieldWorkerWA").value;
const data = {
    data: {
        msg : msg,
        fieldWorker: fieldWorker,
        fieldWorkerNumber: recipient
    }
};
console.log(JSON.stringify(data));
$.ajax({
    type: 'POST',
    url: '@WebApplication1.AppSettings.Path.Deployment' + '/MessageBird/Send',
    headers: {"token": '@WebApplication1.Models.MessageBird.TOKEN'},
    data: JSON.stringify(data),
    contentType: "application/json; charset=utf-8",
    dataType: 'json',
    success: function (result) {
        console.log('success');
    },
    error: function (result) {
        console.log('error');
    }
});

Controller:

public async Task SendAsync([FromBody] JObject jo) // jo always returns null
{
    try
    {
        string apiToken = Request.Headers["token"].ToString();
        if (apiToken.Trim() != Models.MessageBird.TOKEN)
        {
            return;
        }
      
    }
    catch (Exception e) { }
    finally { }
}
Developer technologies ASP.NET ASP.NET Core
{count} votes

2 answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 77,686 Reputation points Volunteer Moderator
    2024-12-12T17:28:50.8433333+00:00

    did you add

    builder.Services.AddControllers().AddNewtonsoftJson();
    

    to get netwonsoft binding support?

    1 person found this answer helpful.
    0 comments No comments

  2. SurferOnWww 4,631 Reputation points
    2024-12-12T01:14:01.7233333+00:00

    Please try creating your custom class (not JObject) as view model which is used to transfer the data form view to controller as described below:

    (1) Create a class to use it as view model. Shown below is a sample:

    public class Data
    {
        public string Msg { get; set; } = string.Empty;
        public string FieldWorker { get; set; } = string.Empty;
        public string FieldWorkerNumber { get; set; } = string.Empty;
    }
    

    (2) Use the above class as the argument of action method:

    [HttpPost]
    public IActionResult Receive([FromBody] Data data)
    {
        var mag = data.Msg;
        var fielsWorker = data.FieldWorker;
        var filedWokerNumber = data.FieldWorkerNumber;
        return Ok();
    }
    

    (3) Send the data using jQuery ajax:

    <input type="button" id="button1" value="Post" class="btn btn-primary" />
    
    @section Scripts {
        <script type="text/javascript">
            window.addEventListener("DOMContentLoaded", () => {
                const btn = document.getElementById("button1");
                btn.addEventListener("click", sendData);
            });
    
            let data = {
                msg : "msg",
                fieldWorker: "fieldWorker",
                fieldWorkerNumber: "recipient"
            };
    
            const sendData = () => {
                $.ajax({
                    type: 'POST',
                    url: '/Home/Receive',
                    data: JSON.stringify(data),
                    contentType: "application/json; charset=utf-8"
                });
            };
        </script>
    }
    

    (4) The data sent by the above script are received by the action method as follows:

    enter image description here

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.