简体   繁体   English

为什么我的带有多个参数的asp mvc ajax GET请求不起作用?

[英]Why is my asp mvc ajax GET request with multiple parameters is not working?

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 我的Javascript代码

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. 该代码非常失败...总是error ,并且警告框始终显示错误。 It never goes to the MyAction action of Home controller whatever format I user for url . 无论我使用url哪种格式,它都不会执行Home控制器的MyAction操作。

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 创建get请求时,您没有任何数据请求,只能使用查询字符串,不能使用Body数据

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");
      }
  });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM