The parameters of my ASP .NET controller method stays null when I send a XmlHttpRequets
from my JavaScript file. The JavaScript debugger shows that the request sends successfully. Why is It not working?
JavaScript function:
function BuyBook(title) {
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("POST", "home/BuyBook", true);
xmlHttp.setRequestHeader("Content-Type", "multipart/form-data");
var order = { BookTitle: title, Quantity: document.getElementById("quantity").value };
xmlHttp.send(JSON.stringify({ order: order }));
console.log(xmlHttp.responseText);
}
Controller method:
[HttpPost]
public IActionResult BuyBook(Models.Order order)
{ .... }
Models.Order class:
public class Order
{
[Required]
public string BookTitle { get; set; }
[Range(1,100)]
public int Quantity { get; set; }
}
Try the following things:
Check that the class signature matches the JSON being sent. For above example, the JSON being sent would look like
{ "BookTitle": title, "Quantity": "value" }
Also I see that the class defines Quantity
as int
, so use parseInt()
to convert Quantity
value into int
. By default document.getElementById(..).value
would give a string.
let quantity = parseInt(document.getElementById("quantity").value);
var order = { BookTitle: title, Quantity: quantity };
Use Content-Type
as application/json
Add [FromBody]
attribute to the model
BuyBook([FromBody]Models.Order order)
xmlHttp.send(order);
OR
xmlHttp.send(JSON.stringify(order));