簡體   English   中英

為什么我的帶有多個參數的asp mvc ajax GET請求不起作用?

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

不好意思發表。 我在這里看到了很多答案,也看到了這個很棒的帖子,但我的電話仍然無法正常工作。 下面是我的配置:

路由配置

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

家庭控制器中的動作方法

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

該代碼非常失敗...總是error ,並且警告框始終顯示錯誤。 無論我使用url哪種格式,它都不會執行Home控制器的MyAction操作。

這是怎么回事 ?

創建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