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

问题描述:

这与下面类似,但没有Ajax.我正在使用JavaScript和XMLHttpRequest

This is similar to below but without Ajax. I am using JavaScript and XMLHttpRequest

AJAX发布数据到达ASP.NET Core 2.1控制器时为空

在ASP.NET MVC中一切正常,但是我正在学习ASP.NET Core MVC.

Home.cshtml中的按钮会在JavaScript方法下面调用,而实习生会在HomeController.cs中调用名为Test的方法.

我的问题是,如果我的测试方法serverName和port中的断点都为空

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)

由于您的内容类型为application/json;charset=UTF-8,因此您需要使用[FromBody]并根据您的情况将数据作为对象接收.

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.

此外,您只能在操作参数中一次使用[FromBody](来自

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

每个操作方法不要将[FromBody]应用于多个参数. ASP.NET Core运行时将读取请求流的职责委托给输入格式化程序.读取请求流后,就不再可以再次绑定其他[FromBody]参数.

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.创建一个ViewModel:

1.Create a 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 });
        }
    }