gpt4 book ai didi

javascript - ASP.NET Core 2.1 MVC 使用 XMLHttpRequest 将数据从 JavaScript 发送到 Action 方法

转载 作者:行者123 更新时间:2023-11-30 19:24:16 25 4
gpt4 key购买 nike

这类似于下面但没有 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 的方法。

我的问题是如果我在我的测试方法中保持断点 serverName 和 port 都是 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 });
}
}

我什至试过下面但没有帮助

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],并根据您的情况将数据作为对象接收.

此外,您只能在 Action 参数中使用一次[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.创建一个 View 模型:

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 });
}
}

关于javascript - ASP.NET Core 2.1 MVC 使用 XMLHttpRequest 将数据从 JavaScript 发送到 Action 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57085268/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com