2012-08-14 27 views
0

我正在做一個驗證例程,需要返回到服務器,執行一些數據庫檢查,然後返回到客戶端顯示消息取決於結果..我使用的是MVC3,Javascript,Ajax。處理成功:和錯誤:在MVC3客戶端到服務器驗證例程使用AJAX

這是我的客戶方:

<script type="text/javascript"> 
$('#usrid').change(function (e) { 

    var formData = $("form").serialize(); 

    $.ajax({ 
     url: "ValidateOfficers", 
     type: "POST", 
     data: formData, 
     success: function (data) { 
      alert(data.reponseText); 
     }, 
     error: function (data) { 
      alert(data.reponseText); 
     } 
    }); 
}); 

這是我的控制器操作:

 [HttpPost, ActionName("ValidateOfficers")] 
    public ActionResult ValidateOfficers(userRole role) 
    { 
     int holderid = role.holderid; 
     int roleSelected = role.roleid; 
     int chosenUser = role.usrid; 
     int countRoles = db.userRoles.Where(i => i.roleid == roleSelected && i.holderid == holderid).Count(); 

     if (countRoles == 0) //success: 
     { 
      Response.StatusCode = 200; 
      Response.Write("ok"); 
      return View("Create", role); 
     } 
     if (countRoles > 0) //error: 
     { 
      Response.StatusCode = 500; 
      Response.Write("error"); 
      return View("Create", role); 
     } 
     return View(); 
    } 

我想做的事情進行計數,然後發回基於該狀態是什麼計數結果..所以如果countRoles = 1,那麼如果countRoles> 1則返回「官員存在」文本,然後「存在重複記錄」。如果countRoles爲零,那麼我可以假設成功並且不提供消息。

好吧,我堅持如何在服務器端構建這個自定義消息,以及如何將其發回給客戶端。我正在考慮在剃刀上添加幾個標籤,並根據計數結果顯示/隱藏。正如您所看到的,我已經有了一個非常基本的工作,但無濟於事。我在當前的警報消息中得到「未定義」。

如果我能得到一些關於此的提示,我將不勝感激!

+0

「我在當前的警報消息中得到」未定義「。這是因爲數據**是您的回覆文本。 – 2012-08-14 10:09:13

+0

好的 - 在這種情況下,我如何使用來自服務器的文本保存數據? – bruceiow 2012-08-14 10:34:27

+0

'alert(data)'顯示什麼? – 2012-08-14 10:49:53

回答

0

行動

public ActionResult ValidateOfficers(userRole role) 
{ 
    string myMessage; 
    \\ here goes all of your other code 
    \\ set value into myMessage depending on your conditions. 

    return Json(new {foo=myMessage}); 
} 

的Javascript

<script type="text/javascript"> 
$('#usrid').change(function (e) { 

    var formData = $("form").serialize(); 

    $.ajax({ 
     url: "ValidateOfficers", 
     type: "POST", 
     data: formData, 
     success: function (data) { 
      alert(data.foo); 

      if(data.foo == "exists") 
      { // do something (show/hide msgs) 
      } 
      else if(data.foo == "duplicate") 
      { // do something else (show/hide msgs) 
      } 
      else 
      { // do something else (show/hide msgs) 
      } 

     }, 
     error: function (data) { 
      alert(data.reponseText); 
     } 
    }); 
}); 

,你也想讀this article,對於知道如何返回JSON數據。

希望這可以解決您的問題。

+0

謝謝 - 這是一篇非常有用的文章和文章。我現在正在處理一件事:-) – bruceiow 2012-08-14 12:15:45

相關問題