2015-05-26 20 views
2

是的,有一大堆類似問題的帖子。我試圖按照他們的答案,但我的ajax調用仍然沒有達到控制器方法。Ajax調用未達到控制器方法

控制器(SalesController.cs):

[HttpGet] 
public JsonResult fillVarietiesSelect(int species_id) 
{ 
    String[] alist = {"a","b","c"}; 
    return Json(alist, JsonRequestBehavior.AllowGet); 
} 

的javascript:

$('#species-select').on('change', function() { 
    var species_id = $('#species-select').val(); 
    console.log("species id selected " + species_id); 
    alert("species id selected " + species_id); 
    $('#variety-select').empty(); 
    $.ajax({ 
     type: 'GET', 
     url: '@Url.Action("fillVarietiesSelect", "Sales")', 
     data: {species_id : species_id}, 
     success: function (result) { 
      alert(result); 
     } 
    }); 
}); 

的上改變事件被解僱,並警告正確的數據彈出。我在控制器方法中設置了一個斷點,但執行似乎並沒有到達那裏。

+0

您是否在控制檯或請求網絡選項卡中看到任何錯誤? –

+0

ASP.NET MVC拋出如此多的控制檯錯誤!但最後一個是:傳遞給getElementById()的空字符串。 jquery-1.10.2.js:188:0 GET XHR http:// localhost:65244/@Url.Action(%22fillVarietiesSelect%22,%20%22Sales%22)' – abalter

+0

網絡面板顯示404錯誤'GET @ Url.Action(「fillVarietiesSelect」,「Sales」)' – abalter

回答

1

嘗試做酷似以下

控制器:

[HttpGet] 
    public ActionResult receive2(string p) 
    { 
     ViewBag.name = p; 
     List<string> lst = new List<string>() { p }; 
     return Json(lst,JsonRequestBehavior.AllowGet); 

    } 

客戶端

 $.ajax({ 
      type: "GET", 
      url: "Main/receive2", // the method we are calling 
      contentType: "application/json; charset=utf-8", 
      data: { "p": $("#txtname").val() }, 
      dataType:"json", 
      success: function (result) { 
       alert("yes"); 
       alert('Yay! It worked!tim' + result); 
       window.location = "http://google.com"; 
       // Or if you are returning something 

      }, 
      error: function (result) { 
       alert('Oh no aa :(' + result[0]); 
      } 

     }); 

我已經檢查了它的工作

+0

這樣做。我認爲問題可能一直試圖調用val而不是字符串,並嘗試將它作爲int發送。 – abalter

0

你的404錯誤是告訴你,@url。操作不被視圖引擎解析。 @是Razor的語法,所以爲了這個工作,你需要使用C#視圖的.cshtml擴展名或VB視圖的.vbhtml擴展名,並使用MVC 3或更高版本。

+0

該視圖是'index.cshtml'。 – abalter

0

我有同樣的問題,改變參數從intstring解決了這個問題。

在服務器端我有,

公共字符串RemoveByDocumentID(INT DocumentID)

改變,要

公共字符串RemoveByDocumentID(字符串DocumentID)

解決了 問題。

在相同的上下文中,我有另一個同名的方法(重載方法)。這也是導致這個問題的原因,所以我讓這個方法名稱獨一無二。