Reputation: 3500
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 ASP.NET MVC but I am learning ASP.NET Core MVC.
A button in Home.cshtml calls below JavaScript method which intern calls a method named Test in HomeController.cs.
My problem is if I keep break point in my Test method serverName and port are both null
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 && 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 });
}
}
I even tried below but none helps
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)
Upvotes: 3
Views: 2972
Reputation: 20116
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 });
}
}
Upvotes: 3