Sorry to post. I saw SO MANY answers here and also this great post but my call is still not working. Below is my config :
Route config
routes.MapRoute(
name: "MyRoute",
url: "{controller}/{action}/{id}/{name}/{age}",
defaults: new { controller = "Home", action = "MyAction"
, id = UrlParameter.Optional
, name = UrlParameter.Optional
, age = UrlParameter.Optional}
);
Action method in home controller
[HttpGet]
public ActionResult MyAction(int id, string name, int age)
{
// Do some work and return View()
}
My Javascript Code
function MyFunction(id)
{
var name = document.getElementById('name').value;
var age = document.getElementById('age').value;
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: {
"id": id,
"name": name,
"age": age
},
// url: '@Url.Action("MyAction", "Home")',
url: '/Home/MyAction',
success: function (response) {
alert("success");
},
error: function (xhr, status, error) {
alert("error");
}
});
}
This code miserably fails... It ALWAYS goes to error
and the alert box shows for error all the time. It never goes to the MyAction
action of Home
controller whatever format I user for url
.
What's going on ?
when you create a get request, you dont have any data request, you can use only query string, not Body data
function MyFunction(id)
{
var name = document.getElementById('name').value;
var age = document.getElementById('age').value;
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: "json",
//data: {
// "id": id,
// "name": name,
// "age": age
//},
// url: '@Url.Action("MyAction", "Home")',
url: '/Home/MyAction/'+id+'/'+name+'/'+age,
success: function (response) {
alert("success");
},
error: function (xhr, status, error) {
alert("error");
}
});
}
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.