2010-12-21 62 views
2

您好我正在使用jQuery的一些AJAX執行窗體的職位。mvc客戶端驗證破了,即時通訊做一個ajax jQuery .post

繼承人我的jquery:

$("#submit").click(function (e) { 
      e.preventDefault(); 
      $.post("Account/LogOn", 
        $(this.form).serialize(), 
        function (data) { 
         if (data.redirect) { 
          // data.redirect contains the string URL to redirect to 
          window.location.href = data.redirect; 
         } 
         else { 
          // data.form contains the HTML for the replacement form 
          $("#error").replaceWith(data.error); 
         } 
        }, 
        'json' 
      ); 
      return false; 
     }); 

可正常工作,但是在內置MVC驗證不再起作用? (錯誤消息不顯示用戶名/密碼,如果它們被省略並且表單被提交)。

任何想法爲什麼clientside驗證不再有效?

感謝

+0

我的第一個猜測是您正在替換的HTML被替換爲無效標記。導致現有的JavaScript驗證不起作用。我需要看到更多的AJAX請求返回。 – 2010-12-21 18:50:20

+0

替換工作正常,它顯示一個字符串「提供的用戶名或密碼不正確。」如果用戶名/密碼組合不存在。我問爲什麼客戶端驗證不再工作了 - 它是一個mvc項目隨附的基本登錄表單btw – raklos 2010-12-21 18:54:45

回答

2

由於客戶端驗證是通過表單提交觸發,你不再發布形式,則執行的是jQuery的崗位基本上繞過驗證觸發。你必須在你的javascript中手動觸發驗證,而不是檢查客戶端驗證是否發現任何錯誤,如果沒有,你可以繼續使用ajax文章。

編輯:Here's the documentation如何做到這一點。該代碼將看起來類似於此....

$("#submit").click(function (e) { 
      e.preventDefault(); 
      $(this.form).validate(); 
      if($(this.form).valid()) 
{ 
      $.post("Account/LogOn", 
        $(this.form).serialize(), 
        function (data) { 
         if (data.redirect) { 
          // data.redirect contains the string URL to redirect to 
          window.location.href = data.redirect; 
         } 
         else { 
          // data.form contains the HTML for the replacement form 
          $("#error").replaceWith(data.error); 
         } 
        }, 
        'json' 
      ); 
      return false; 
} 
     });