Passing parameters when calling ajax

I am trying to make an ajax call to a controller method. Without a parameter, it works fine. As soon as I add a parameter, I always get a zero parameter in the controller. I think I correctly executed the parameter passing in the 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); } 
+4
source share
3 answers

This is because you are processing 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 this, here is how you do it:

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

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}, .... 
+3
source

Try to specify:

 data: { stockID : dropDownID }, 

It looks like you are passing "stockID" not stockID . Fiddler is a good tool for this, it will allow you to see if the Controller action has been performed and what data has been sent to the server.

+2
source

Source: https://habr.com/ru/post/1479491/


All Articles