2017-03-03 80 views
1

我正在下面ajax呼叫我的MVC應用程序時使用parameter它不工作(控制器是沒有得到所謂的)。 效果很好,當我刪除兩個ajax通話和controller參數。

//代碼:

$('#btnGw').click(function (e) {    

       $.post("../api/cuews/", { openId: "3" }, function (data) { 

        // data to manipulate for filter values 

       });    

      }); 

//控制器

[HttpPost] 
    public string Post(string openId) 
    { 
     string json = openId; 

     return json; 
    } 

嘗試添加Json.Stringify,

$.post("../api/cuews/", { openId: Json.Stringify("3") }, function (data) { 

        // data to manipulate for filter values 

       }); 

$.post("../api/cuews/", Json.Stringify({ openId: "3" }), function (data) { 

        // data to manipulate for filter values 

       }); 

但結果是一樣的。

錯誤:(在控制檯)

POST http://localhost/api/cuews/ 404 (Not Found) 

我在做什麼錯誤的參數?

僅供參考,

相同的結構適用於$.get與參數。

+0

既然你得到了404我不相信你的API調用地址是正確的 - 你的控制器和路由是什麼樣的? –

+0

@KallumTanton我想知道它適用於'.get()'。 – iamCR

+0

哪個jQuery方法適用於GET? –

回答

1

試試這個,

  1. 創建具有所需性能的模型。
  2. 將模型作爲參數傳遞
  3. 確保從AJAX傳遞的參數與模型中的參數相同(TEXT)。

如:

public class TestModel 
{ 
    public int ID { get; set; } 
    public string Desc { get;set; } 
} 

$.ajax({ 
    url: '../api/Test/', 
    type: 'POST', 
    dataType: 'json', 
    data: JSON.stringify({ Id: "1", Desc : "Name" }), 
    contentType: "application/json; charset=utf-8", 
    success: function (data) { 
        alert("Success!!!") 
       }, 
    error: function (xhrequest, ErrorText, thrownError) { 
         alert("Error") 
       } 
}); 

AJAX效果很好,當這些國家的PARAMS。只是一個解決辦法。

-1

你爲什麼不嘗試:

$.ajax({ 
        type: "POST", 
        contentType: "application/json;charset=utf-8",//type of data to be send 
        url: youraddressgoeshere 
        dataType: "json",//type of data to be received 
        data: JSON.stringify(model),//data to be send 
        async: false, 
        success: function (response) { 
         //some code 
        }, 
        error: function (xhr, status, error) {  
         alert(xhr.responseText); 
        } 
     }); 

您價值整體對象轉換JSON.stringify不能及的。嘗試轉換整個對象並將其傳遞給您的serverside方法。

此外,

如果你是在ASP.NET MVC工作去RouteConfig在App_Start文件夾,檢查你是如何定義的URL

FOR EX:

routes.MapRoute(
       name: "Default", 
       url: "{controller}/{action}/{id}", 
       defaults: new { controller = "Home", action = "Login", id = UrlParameter.Optional } 
      ); 

通知{controller}/{action}/{id}這裏我有{id}參數。因此,如果我是你,我會嘗試在服務器端控制方法改變public string Post(string openId)public string Post(string id)

+0

嘗試什麼?解釋爲什麼它應該起作用。 – Justinas

+0

@Justinas我正在編輯答案和解釋。如果只有你在投票前等了一會兒。 – Arbaaz

+0

@Arbaaz看到我的第二個選項,我嘗試了相同的。它仍然沒有工作。 – iamCR

0

你的問題是,你使用$ _ POST發送參數,並且您public string Post(string openId)請求參數在$_GET傳遞。嘗試將此參數分配移至函數內部。

+0

我已經更新了這個問題。你說這個嗎?如果是的話,那麼它也是一樣的。沒有工作 – iamCR

+0

控制器參數看起來很好 - OP已經正確使用了「HttpPost」裝飾器。 –