简体   繁体   English

如何从Js fetch()获取数据到服务器?

[英]How to get data to the server from Js fetch ()?

I try to transfer data from js to the server, but I get "null".我尝试将数据从 js 传输到服务器,但我得到“null”。

My js:我的js:

async function sort(param) {
        let classList = param.classList;
                    //"DateCreate"     //Ascending
        console.log(param.id + " " + classList[0]);
       let response = await fetch("/Amendment/Sort", {
            method: "POST",
            body: JSON.stringify({ sortValue : param.id, sortType : classList[0]})
        });
        if (response.ok) {
            let responseHtml = await response.text();
            document.getElementsByClassName("result").innerHTML = responseHtml;
            alert("OK");
        } else {
            alert("Error HTTP: " + response.status);
        }

In browser:在浏览器中:

在此处输入图片说明

Server's method (Controller: Amendment):服务器的方法(控制器:修正):

  [HttpPost]
                                    //null           //null
  public IActionResult Sort(string sortValue, string sortType )
  {
         //*****//
      return PartialView("_TableData", model);
  }

Solution 1:解决方案1:

You need to use the [FromBody] attribute as your request body contains sortValue and sortType .您需要使用[FromBody]属性,因为您的请求正文包含sortValuesortType

Also make a class with sortValue and sortType string properties and in controller action method, use that class as parameter.还创建一个具有sortValuesortType字符串属性的类,并在控制器操作方法中使用该类作为参数。

Soluttion 2:解决方案2:

Instead of putting sortValue and sortType in body, sending it from url.不是将sortValuesortType放在 body 中,而是从 url 发送它。

var url = "/Amendment/Sort?sortValue=" + param.id + "&sortType=" + classList[0];
let response = await fetch(url, {
    method: "POST"
});

The problem resides in the way the framework binds the values you post to the parameters of this action method.问题在于框架将您发布的值绑定到此操作方法的参数的方式。 If you define a class like the following one:如果您定义一个类,如下所示:

public class SortModel
{
    public string SortValue { get; set; }
    public string SortType { get; set; }
}

and then use this class as the only parameter of your action method then the framework will bind correctly the posted values.:然后使用此类作为您的操作方法的唯一参数,然后框架将正确绑定发布的值。:

[HttpPost]
public IActionResult Sort(SortModel sortModel)
{
     // Then use 
     //   - sortModel.SortValue
     //   - sortModel.SortType
}

For further options, you can read this .有关更多选项,您可以阅读

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM