Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing parameters in ajax call

I'm trying to make an ajax call to the controller method. without parameter it works fine. Once i add the parameter i always receive a null parameter to the cotroller. I think i have correctly done the parameter passing in ajax call.

 <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>

Controller:

 [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);

        }
like image 946
chamara Avatar asked Dec 03 '22 23:12

chamara


2 Answers

It's because you are treating the data as a string

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

you can change it to:

data: { stockID: dropDownID },

in some cases, depending on the parameter declared in your controller method, you need to serialize the data. If you need to do that then this is how you would do it:

var o = { argName: some_value };
$.ajax({
    // some other config goes here
    data: JSON.stringify(o),
});
like image 165
von v. Avatar answered Dec 12 '22 02:12

von v.


try 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},
                ....
like image 22
AliRıza Adıyahşi Avatar answered Dec 12 '22 02:12

AliRıza Adıyahşi