Ajax操作始终返回true

时间:2012-04-10 14:17:59

标签: jquery ajax asp.net-mvc-3

我正在尝试使用ajax进行一些验证。它从我的MVC3控制器调用一个方法,但无论控制器返回true还是false,它都返回true。始终显示警报。

ClientChoices / HasJobInProgress

 public Boolean HasJobInProgress(int clientId)
        {
            return false;
            //return _proxy.GetJobInProgress(clientId);
        }

Jquery.Ajax

 $("#saveButton").click(function() {
        var hasCurrentJob =  
            $.ajax({
            url: '@Url.Action("HasJobInProgress", "ClientChoices")/',
            data: { id: @Model.ClientId },
            success: function(data){
                return data;
            }
            });
        if (hasCurrentJob) {
            alert("The current clients has a job in progress. No changes can be saved until current job completes");
        } 
    });

$("#saveButton").click(function() {
            $.ajax({
            url: '@Url.Action("HasJobInProgress", "ClientChoices")/',
            data: { id: '@Model.ClientId' },
            success: function(data){
                showMsg(data);
            },
            cache: false
        });
    });

    function showMsg(hasCurrentJob) {
          if (hasCurrentJob.toString()=="True") {
               alert("The current clients has a job in progress. No changes can be saved until current job completes");
          } 
    }

1 个答案:

答案 0 :(得分:3)

AJAX调用是异步的,您的返回数据不会设置hasCurrentJob的值,而是返回成功回调。请参阅下文,了解如何根据data显示提醒。

    $("#saveButton").click(function() {
        //var hasCurrentJob
            $.ajax({
            url: '@Url.Action("HasJobInProgress", "ClientChoices")/',
            data: { id: @Model.ClientId },
            success: function(data){
                showMsg(data);
            }
            });

    });

    function showMsg(hasCurrentJob) {
          if (hasCurrentJob === 'true') {
               alert("The current clients has a job in progress. No changes can be saved until current job completes");
          } 
    }