Skip to main content
 首页 » 编程设计

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

2024年01月22日44shanyou

抱歉发帖。我在这里看到了很多答案,还有 this great post但是我的电话还是打不通。下面是我的配置:

路由配置

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

家庭 Controller 中的操作方法

[HttpGet] 
public ActionResult MyAction(int id, string name, int age) 
{  
    // Do some work and return View() 
} 

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

此代码惨遭失败...它总是转到错误 并且警告框始终显示错误。无论我为 url 使用什么格式,它都不会进入 Home Controller 的 MyAction 操作。

这是怎么回事?

请您参考如下方法:

创建get请求时,没有任何数据请求,只能使用query string,不能使用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"); 
      } 
  }); 
}