这与下面类似,但没有 Ajax。我正在使用 JavaScript 和 XMLHttpRequest
AJAX post数据到达ASP.NET Core 2.1控制器时为空 https://stackoverflow.com/questions/51336590/ajax-post-data-is-null-when-it-reaches-the-asp-net-core-2-1-controller
ASP.NET MVC 中的一切都运行良好,但我正在学习 ASP.NET Core MVC。
Home.cshtml 中的按钮调用下面的 JavaScript 方法,该方法实习生调用 HomeController.cs 中名为 Test 的方法。
我的问题是,如果我在测试方法中保留断点,服务器名称和端口均为空
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 });
}
}
我什至在下面尝试过,但没有任何帮助
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)