I am trying to get data from server by ajax.
Here's my ajax request:
$.ajax({
type: 'post',
contentType: "application/json; charset=utf-8",
url: '@Url.Action("GetData", "MyController")',
dataType: "json",
data: { 'skip': '5' },
success: function (data) {
alert(data);
},
error: function (jqXHR, textStatus, errorThrown) {
alert("error: STATUS = " + textStatus + "ERROR = " + errorThrown);
}
});
and my action:
[HttpPost]
public ActionResult GetData(string skip)
{
return new JsonResult() {Data = "test"};
}
with this code I get 404 not found error
, when I remove the HttpPost
attribute I get Internal Server Error
.
Change your AJAX url so it resembles the format:
url: "controller/action"
So in your case,
url: "MyController/GetData"
You could also try formatting your data field differently. For instance:
data: "&skip=" + "5",
Use this Javascript function to get all types of URL:
function rootUrl(url) {
var _rootUrl = '@Url.Content("~")';
var x = url;
if (url.indexOf(_rootUrl) != 0) {
x = _rootUrl + "/" + url;
x = x.replace(/\/\//g, "/").replace(/\/\//g, "/");
}
return x;
};
then Use URL in your AJAX request as::
url: rootUrl("MyController/GetData")
Add attribute [FromBody] and action selector will not look for query string parameter
[HttpPost]
public ActionResult GetData([FromBody]string skip)
{
return new JsonResult() {Data = "test"};
}
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.