JQuery ajax controller call

I'm new to Ajax, and I'm trying to turn off the checkbox if certain items are selected from the drop-down list. I need to pass the GetMlaDeliveryType (int Id) method to RecipientsController.cs in mlaId.

I'm not quite sure how to set up ajax call in javascript function checkMlaDeliveryType (mlaId).

// MLA Add disable express checkbox if delivery type is electronic $('.AddSelectedMla').change(function () { var deliveryType = checkMlaDeliveryType($('.AddSelectedMla').val()); // disable express option if delivery type is Electronic if (deliveryType == "Mail") { $(".mlaExpressIndicator").removeAttr("disabled"); }else{ $(".mlaExpressIndicator").attr('checked', false).attr("disabled", true); } }) // ajax call to get delivery type - "Mail" or "Electronic" function checkMlaDeliveryType(mlaId) { $.ajax({ type: "GET", url: "/Recipients/GetMlaDeliveryType/" , data: mlaId, dataType: , success: }); } RecipientsController.cs public string GetMlaDeliveryType(int Id) { var recipientOrchestrator = new RecipientsOrchestrator(); // Returns string "Electronic" or "Mail" return recipientOrchestrator.GetMlaDeliveryTypeById(Id); } 

EDIT:

This is what the latest javascript looked like that worked

 // MLA Add disable express checkbox if delivery type is electronic $('.AddSelectedMla').change(function () { checkMlaDeliveryType($('.AddSelectedMla').val()); }) // ajax call to get delivery type - "Mail" or "Electronic" function checkMlaDeliveryType(mlaId) { $.ajax({ type: 'GET', url: '@Url.Action("GetMlaDeliveryType", "Recipients")', data: { id: mlaId }, cache: false, success: function (result) { // disable express option if delivery type is Electronic if (result == "Mail") { $(".mlaExpressIndicator").removeAttr("disabled"); } else { $(".mlaExpressIndicator").attr('checked', false).attr("disabled", true); } } }); } 
+4
source share
2 answers
 $.ajax({ type: 'GET', url: '/Recipients/GetMlaDeliveryType', data: { id: mlaId }, cache: false, success: function(result) { } }); 

then fix the action of your controller so that it returns an ActionResult, not a string. JSON would be appropriate in your case:

 public string GetMlaDeliveryType(int Id) { var recipientOrchestrator = new RecipientsOrchestrator(); // Returns string "Electronic" or "Mail" return Json( recipientOrchestrator.GetMlaDeliveryTypeById(Id), JsonRequestBehavior.AllowGet ); } 

Now your callback will be passed directly to the javascript instance of your model. You do not need to specify any dataType parameters:

 success: function(result) { // TODO: use the result here to do whatever you need to do } 
+7
source

Set data in the Ajax call so that its key matches the parameter on the controller (i.e., Id ):

 data: { Id: mlaId }, 

Note also that it is better to use @Url.Action(actionName, controllerName) to get the action URL:

 url: '@Url.Action("GetMlaDeliveryType", "Recipients")' 
+5
source

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


All Articles