2016-09-18 26 views
1

與參數MVC jQuery的AJAX調用與輸入參數

在控制器我有以下動作調用控制器上的動作時,我面臨一個問題:

[HttpPost] 
public ActionResult UpdateData(string month) 
{ 
    return Json(new { success = true, message = "Hello world" }); 
} 

在Ajax調用視圖的樣子:

$.ajax({ 
    url: '@Url.Action("UpdateData")', 
    dataType: "json", 
    type: "POST", 
    contentType: 'application/json; charset=utf-8', 
    cache: false, 
    data: { }, 
    success: function (data) { 
     if (data.success) { 
      alert(data.message); 
     } 
    }, 
    error: function (xhr) { 
     alert(xhr.responseText); 
    } 
}); 

這個效果很好,但是當我想通過像

參數

我得到一個錯誤,這個動作永遠不會被調用。我只是沒有看到它。


編輯:

好吧,我不得不通過JSON作爲一個字符串:

data: "{month:'may'}" 

我想我需要更多的睡眠:-)

+0

請注意,model-view-controller標籤用於提供有關該模式的問題。沒有爲ASP.NET-MVC實現特定的標籤。 –

+1

你需要做的是刪除'contentType:'application/json; charset = utf-8','並使用'data:{month:'may'}' –

+0

它的工作原理,謝謝!我將在下次使用asp.net-mvc標籤;-) – Alpine13

回答

0

你必須只是刪除內容類型更好如果你在URL中傳遞控制器名稱

$.ajax({ 
     url: '@Url.Action("UpdateData","YourControllerName")', 
     dataType: "json", 
     type: "POST",    
     cache: false, 
     data: {month:'may'} , 
     success: function (data) { 
      if (data.success) { 
       alert(data.message); 
      } 
     }, 
     error: function (xhr) { 
      alert(xhr.responseText); 
     } 
});