I have a simple controller method that expects to receive a string argument:
public class ZTest : BaseController
{
[HttpPost]
public async Task<ActionResult> Test(string msg)
{
// BREAKPOINT msg is always null here
return Json(ModelState.ToDataSourceResult());
}
}
A basic Ajax request posts data to the controller method:
$.ajax({
type: 'POST',
url: '@Url.Action("Test", "ZTest")',
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ msg: "Hello World" }),
success: function (data) {
if (data.exception) {
Swal.fire("Error", data.message, "error");
}
else {
Swal.fire("Success", "message", "success");
}
}
});
Why would this simple example fail?
I created this simple MRE while trying to troubleshoot a more involved example.
I have experimented with adding and removing the [HttpPost]
decoration, prepending the string msg
variable with [FromBody]
, and removing the Ajax properties dataType
and contentType
.
Now we're using contentType: "application/json; charset=utf-8"
,this means that the JSON object sent will be bound to the object(Message) in C#.
Here is the test code in my side
[HttpPost]
public IActionResult Test([FromBody] Message msg)
{
return Json(msg);
}
public class Message
{
public string? msg { get; set; }
}
Test Result