Asp.net-Mvc

jQuery.Validation.Unobtrusive 客戶端驗證僅在腳本位於視圖頁面上時有效

  • June 18, 2013

我有一個使用jQuery.validation.js外掛和 MVC 的jQuery.validation.unobtrusive.js的****ASP.NET MVC 4 應用程序。我在視圖模型上使用數據註釋來驗證文本框的輸入是否為整數。

此(嵌套)視圖使用…載入到父視圖中

<% Html.RenderPartial("New"); %>

第一個初始頁面載入,客戶端驗證工作。但是任何使用 ajax 呼叫重新載入嵌套視圖,客戶端驗證不再有效。這是為什麼?

更新:(來自以下webdeveloper解決方案的程式碼範例)

$.validator.unobtrusive.parse($('form'));

例子:

var saveAndUpdate = function (url) {
   var myForm = $('form', $('#TheDivThatContainsTheNewHTML'));
   $.ajax({
       url: url,
       type: 'POST',
       data: myForm.serialize(),
       success: function (result) {
           $('#TheDivThatContainsTheNewHTML').html(result);
           $.validator.unobtrusive.parse($('#TheDivThatContainsTheNewHTML'));          
       },
       error: function (xhr, ajaxOptions, thrownError) {
           alert(xhr.status);
           alert(thrownError);
       },
       dataType: 'html'
   });
}

But any reloading of the nested view with an ajax call, client side validation no longer works. Why is that?

驗證適用於document ready,當您刷新頁面時,您應該手動為您的表單初始化驗證。

像這樣:

$.validator.unobtrusive.parse("form");

同樣的問題:jquery.validate.unobtrusive 不使用動態注入的元素

引用自:https://stackoverflow.com/questions/16105170