2012-04-10 128 views
1

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

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"); 
     } 
    }); 

SOLUTION

$("#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"); 
      } 
    } 

回答

3

AJAX调用是异步以及返回的数据将不会设置在V可能是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"); 
      } 
    } 
+0

似乎根本没有工作。警报不会在任何情况下显示。 – 2012-04-10 14:50:04

+0

@atbyrd你看到任何脚本错误?你可以在showMsg函数中设置一个警报,看看它是否被调用?另外'alert(data)'检查返回的值。 – 2012-04-10 14:54:13

+0

重建并强制重新加载之后,它就可以正常工作。但与以前相同的结果。 – 2012-04-10 15:01:04