jQuery Ajax调用控制器
我是Ajax的新手,如果在下拉列表中选择了某些项目,我会尝试禁用复选框。 我需要将mlaId传递给RecipientsController.cs中的GetMlaDeliveryType(int Id)方法。
我不确定如何在javascript函数checkMlaDeliveryType(mlaId)中设置ajax调用。
// 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); }
编辑:
这是最终的javascript看起来如何工作
// 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); } } }); }
$.ajax({ type: 'GET', url: '/Recipients/GetMlaDeliveryType', data: { id: mlaId }, cache: false, success: function(result) { } });
然后修复你的控制器动作,使它返回一个ActionResult,而不是一个字符串。 JSON适用于您的情况:
public string GetMlaDeliveryType(int Id) { var recipientOrchestrator = new RecipientsOrchestrator(); // Returns string "Electronic" or "Mail" return Json( recipientOrchestrator.GetMlaDeliveryTypeById(Id), JsonRequestBehavior.AllowGet ); }
现在,您的成功回调将直接传递给您的模型的javascript实例。 您无需指定任何dataType
参数:
success: function(result) { // TODO: use the result here to do whatever you need to do }
在Ajax调用中设置data
,使其键与控制器上的参数匹配(即Id
):
data: { Id: mlaId },
另请注意,使用@Url.Action(actionName, controllerName)
获取操作URL是一种更好的做法:
url: '@Url.Action("GetMlaDeliveryType", "Recipients")'