did you add
builder.Services.AddControllers().AddNewtonsoftJson();
to get netwonsoft binding support?
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
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 { }
}
did you add
builder.Services.AddControllers().AddNewtonsoftJson();
to get netwonsoft binding support?
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: