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

标签 c# ajax asp.net-mvc

抱歉发帖。我在这里看到了很多答案,还有 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");
      }
  });
}

关于c# - 为什么我的带有多个参数的 asp mvc ajax GET 请求不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43550459/

相关文章:

jquery - Bootstrap Toggle开关在ajax加载并调用事件2次时不起作用

javascript - 有没有办法更新 HTML 中定义的现有数组?

c# - 将 MVC PartialView 渲染到 SignalR 响应中

ajax - ASP.Net MVC : Can you use Data Annotations/Validation with an AJAX/jQuery call?

javascript - 未经授权的 AJAX 请求返回状态代码 200 而不是 401

cpu - 如何使用 C# 访问 CPU 温度读数?

c# - 如何在 C# 中使用 ffmpeg 将视频转换为图像文件?

c# - 将网络浏览器用于多个页面

php - 具有不同 JSON 响应的 Ajax 调用

c# - XmlReader.Name 返回空值