这与下面类似,但没有 Ajax。我正在使用 JavaScript 和 XMLHttpRequest
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)
最佳答案
由于您的内容类型是 application/json;charset=UTF-8
,因此您需要使用 [FromBody]
并根据您的情况将数据作为对象接收.
此外,您只能在操作参数中使用一次[FromBody]
(来自 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.
您可以按照以下步骤正确传递数据:
1.创建ViewModel:
public class ServerModel
{
public string serverName { get; set; }
public string port { get; set; }
}
2.操作:
[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 });
}
}
关于javascript - ASP.NET Core 2.1 MVC 使用 XMLHttpRequest 将数据从 JavaScript 发送到 Action 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57085268/