Skip to content Skip to sidebar Skip to footer

ASP.NET Core 2.1 MVC Send Data From JavaScript To Action Method Using XMLHttpRequest

This is similar to below but without Ajax. I am using JavaScript and XMLHttpRequest AJAX post data is null when it reaches the ASP.NET Core 2.1 controller Everything works good in

Solution 1:

Since your content type is application/json;charset=UTF-8, you need to use [FromBody] and receive the data as an object based on your situation.

Besides, you could only use [FromBody] in the action parameters once(from here)

Don't apply [FromBody] to more than one parameter per action method. The ASP.NET Core runtime delegates the responsibility of reading the request stream to the input formatter. Once the request stream is read, it's no longer available to be read again for binding other [FromBody] parameters.

You could follow below steps to pass data correctly:

1.Create a ViewModel:

public class ServerModel
{
    public string serverName { get; set; }
    public string port { get; set; }
}

2.Action:

[HttpPost]
    public JsonResult Test([FromBody] ServerModel data)
    {
        try
        {
            if (string.IsNullOrEmpty(data.serverName) ||
                string.IsNullOrEmpty(data.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 });
        }
    }

Post a Comment for "ASP.NET Core 2.1 MVC Send Data From JavaScript To Action Method Using XMLHttpRequest"