How to pass parameter from Ajax Request to Web API Controller?

会有一股神秘感。 提交于 2019-12-11 12:14:36

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!