title: ASP.NET Core 2.1 MVC send data from JavaScript to Action method using XMLHttpRequest
body: <p>This is similar to below but without Ajax. I am using JavaScript and XMLHttpRequest</p>
  
  <p><a href="https://stackoverflow.com/questions/51336590/ajax-post-data-is-null-when-it-reaches-the-asp-net-core-2-1-controller">AJAX post data is null when it reaches the ASP.NET Core 2.1 controller</a></p>
  
  <p><strong>Everything works good in ASP.NET MVC but I am learning ASP.NET Core MVC.</strong></p>
  
  <p><strong>A button in Home.cshtml calls below JavaScript method which intern calls a method named Test in HomeController.cs.</strong> </p>
  
  <p><strong>My problem is if I keep break point in my Test method serverName and port are both null</strong></p>
  
  <pre><code>function MyMethod() {
      var xmlhttp = new XMLHttpRequest();
      var url = "/Home/Test";
      var input = {};
      input.serverName = document.getElementById("serverName").value;
      input.port = document.getElementById("port").value;
      xmlhttp.onreadystatechange = function () {
          if (xmlhttp.readyState == 4 &amp;&amp; xmlhttp.status == 200) {
              var jsResp = JSON.parse(xmlhttp.responseText);
              if (jsResp.Status == "Success") {
                  //show success
              }
              else {
                  //show error
              }
          }
      }
      xmlhttp.open("POST", url, true);
      xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
      xmlhttp.send(JSON.stringify(input));
  }
  
  
  
  [HttpPost]
   public JsonResult Test(string serverName, string port)
   {
     try
       {
          if (string.IsNullOrEmpty(serverName) ||
              string.IsNullOrEmpty(port))
           {
              return Json(new { Status = "Error", Message = "Missing Data" });
           }
          else 
           {
          return Json(new { Status = "Success", Message = "Got data" });
           }
         }
         catch (Exception e)
          {
               return Json(new { Status = "Error", Message = e.Message });
          }
   }
  </code></pre>
  
  <p>I even tried below but none helps</p>
  
  <pre><code>public JsonResult Test(JObject serverName, JObject port) -- controller method not hiting
  
  public JsonResult Test(object serverName, object port) -- not allowing me to cast into string
  
  public JsonResult Test([FromBody] string serverName, [FromBody] string port)
  </code></pre>