Search code examples
javascriptasp.netxmlhttprequest

Why Javascript POST Request to ASP.NET controller action getting NULL parameter?


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

Solution

  • Try the following things:

    1. Check that the class signature matches the JSON being sent. For above example, the JSON being sent would look like

      { "BookTitle": title, "Quantity": "value" }
      
    2. 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 };
      
    3. Use Content-Type as application/json

    4. Add [FromBody] attribute to the model

      BuyBook([FromBody]Models.Order order)
      
    5. Send the order object like below.
      xmlHttp.send(order);
      
      OR
      xmlHttp.send(JSON.stringify(order));