I try to transfer data from js to the server, but I get "null".
My 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:
You need to use the [FromBody]
attribute as your request body contains sortValue
and sortType
.
Also make a class with sortValue
and sortType
string properties and in controller action method, use that class as parameter.
Soluttion 2:
Instead of putting sortValue
and sortType
in body, sending it from 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 .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.