5

我是 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);
            }
        }
    });

}
4

2 回答 2

13
$.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
}
于 2012-09-24T05:53:10.477 回答
5

在 Ajax 调用中设置data,使其键与控制器上的参数匹配(即Id):

data: { Id: mlaId },

另请注意,使用@Url.Action(actionName, controllerName)获取操作 URL 是一种更好的做法:

url: '@Url.Action("GetMlaDeliveryType", "Recipients")'
于 2012-09-24T05:53:09.133 回答