2013-05-07 54 views
4

我正在嘗試調用控制器方法的ajax調用。沒有參數,它工作正常。一旦我添加參數,我總是收到一個空參數給cotroller。我想我已經正確地完成了在ajax調用中傳遞的參數。在Ajax調用中傳遞參數

<script type="text/javascript"> 
     $(document).ready(function() { 
      $('#lstStock').change(function() { 
       var serviceURL = '<%= Url.Action("GetStockPrice", "Delivery") %>'; 
       var dropDownID = $('select[id="lstStock"] option:selected').val(); 
      alert(dropDownID); // here i get the correct selected ID 
       $.ajax({ 
        type: "POST", 
        url: serviceURL, 
        data: '{"stockID":"' + dropDownID + '"}', 
        contentType: "application/json; charset=utf-8", 
        dataType: "json", 
        success: successFunc, 
        error: errorFunc 
       }); 

       function successFunc(data, status) { 

        alert(data.Result); 


       } 

       function errorFunc() { 
        alert('error'); 
       } 
      }) 
     }); 
    </script> 

控制器:

[HttpGet] 
     public ActionResult GetStockPrice() 
     { 
      return View(); 
     } 

     [HttpPost] 
     [ActionName("GetStockPrice")] 
     public ActionResult GetStockPrice1(string stockID)//I get the null parameter here 
     { 
      DeliveryRepository rep = new DeliveryRepository(); 
      var value = rep.GetStockPrice(stockID); 
      return Json(new { Result = value }, JsonRequestBehavior.AllowGet); 

     } 

回答

12

這是因爲你是治療的數據作爲一個字符串

data: '{"stockID":"' + dropDownID + '"}', 

,你可以把它改成:

data: { stockID: dropDownID }, 
在某些情況下

,取決於在你的控制器方法中聲明的參數,你需要序列化數據。如果你需要做的,那麼這是你會怎麼做:

var o = { argName: some_value }; 
$.ajax({ 
    // some other config goes here 
    data: JSON.stringify(o), 
}); 
+1

與您的解決方案,我也必須刪除contentType:「application/json; charset = UTF-8」,然後纔開始工作。任何想法? – chamara 2013-05-07 09:00:08

+1

你需要'contentType:「application/json」'在進行stringify時告訴瀏覽器將數據作爲json發送。默認的contentType在傳遞諸如'{stockID:dropDownID}'的數據時會起作用,因爲它被解釋爲有效的json對象/數據。 – 2013-05-07 09:11:19

2

嘗試指定:

data: { stockID : dropDownID }, 

它看起來像你傳遞了"stockID"stockID。 一個很好的工具是Fiddler,它可以讓你看到控制器動作是否被命中以及哪些數據被髮送到服務器。

+0

與您的解決方案我也不得不刪除的contentType:「應用/ JSON的;字符集= UTF-8」,那麼只有它開始工作。任何想法? – chamara 2013-05-07 09:01:17

3

嘗試data: { stockID : dropDownID},

$('#lstStock').change(function() { 
    var serviceURL = '<%= Url.Action("GetStockPrice", "Delivery") %>'; 
    var dropDownID = $('select[id="lstStock"] option:selected').val(); 
        // $(this).val(); is better 
     alert(dropDownID); // here i get the correct selected ID 
      $.ajax({ 
       type: "POST", 
       url: serviceURL, 
       data: { stockID : dropDownID}, 
       .... 
+0

與您的解決方案,我也必須刪除contentType:「應用程序/ JSON;字符集= UTF-8」,然後纔開始工作。任何想法? – chamara 2013-05-07 09:00:38

+0

檢查[這裏](http://api.jquery.com/jQuery.ajax/) – 2013-05-07 09:04:16