2012-04-10 30 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