问题
I am looking for the way to pass the parameter from Ajax Request to Web API Controller in ASP.Net Core like query string in classic ASP.
I have tried below but it did not worked.
View:
"ajax":
{
"url": "/api/APIDirectory/GetDirectoryInfo?reqPath=@ViewBag.Title"
"type": "POST",
"dataType": "JSON"
},
Controller:
[HttpPost]
public IActionResult GetDirectoryInfo(string reqPath)
{
string requestPath = reqPath;
// some code here..
}
Can anyone please advise the ways available to achieve this in asp.net core web api?
回答1:
"ajax":
{
"url": "/api/APIDirectory/GetDirectoryInfo"
"type": "POST",
"dataType": "JSON",
"data": {"reqPath":"@ViewBag.Title"}
}
Edited: If we use query string, we can use the type as GET.
But we are using POST method, so we need to pass the data with the param "data".
回答2:
When posting data in query string use the content type application/x-www-form-urlencoded
$.ajax({
type: "POST",
url: "/api/APIDirectory/GetDirectoryInfo?reqPath=" + @ViewBag.Title,
contentType: "application/x-www-form-urlencoded"
});
Also, make sure that the ajax syntax is correct (I use jQuery in my example) and that the @ViewBag is not included in the string.
Then add the [FromUri] parameter in the controller to make sure the binding reads from the uri
[HttpPost]
public IActionResult GetDirectoryInfo([FromUri]string reqPath)
{
string requestPath = reqPath;
// some code here..
}
来源:https://stackoverflow.com/questions/42408150/how-to-pass-parameter-from-ajax-request-to-web-api-controller