4

我正在尝试对控制器方法进行 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);

        }
4

3 回答 3

12

这是因为您将数据视为字符串

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

您可以将其更改为:

data: { stockID: dropDownID },

在某些情况下,根据控制器方法中声明的参数,您需要序列化数据。如果你需要这样做,那么你会这样做:

var o = { argName: some_value };
$.ajax({
    // some other config goes here
    data: JSON.stringify(o),
});
于 2013-05-07T08:19:50.487 回答
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},
                ....
于 2013-05-07T08:18:45.360 回答
2

尝试指定:

data: { stockID : dropDownID },

看起来你"stockID"没有放弃stockID。一个很好的工具是 Fiddler,它可以让你查看控制器动作是否被命中以及哪些数据被发送到服务器。

于 2013-05-07T08:17:56.953 回答