2013-05-07 60 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