简体   繁体   English

如果通过ajax加载部分,则不会触发ASP.NET MVC Jquery验证

[英]ASP.NET MVC Jquery validation won't fire if partial is loaded via ajax

I'm using the jquery validation option to perform client side validation on an partial view. 我正在使用jquery验证选项在部分视图上执行客户端验证。 The partial view is loaded via ajax into a modal dialog using the url (almost like Html.RenderAction). 部分视图通过ajax加载到使用url的模态对话框中(几乎像Html.RenderAction)。

However, when the partial view is loaded the validation metadata is not being output to the page.Normally you would see something like this: 但是,加载局部视图时,验证元数据不会输出到页面。通常,您会看到如下内容:

//<![CDATA[
3if (!window.mvcClientValidationMetadata) { window.mvcClientValidationMetadata = []; }
4window.mvcClientValidationMetadata.push({"Fields":[],"FormId":"form0","ReplaceValidationSummary":false});
5//]]> 

My question is very similiar to this one ASP.NET MVC 2 loading partial view using jQuery - no client side validation but I don't want to have to use Microsoft validation as I am familiar with jQuery.validate. 我的问题非常类似于这个使用jQuery加载局部视图的ASP.NET MVC 2 - 没有客户端验证,但我不想使用Microsoft验证,因为我熟悉jQuery.validate。

If I understood your problem correctly then this might help. 如果我理解你的问题,那么这可能会有所帮助。

In the example below I am using Ajax.BeginForm to update div(id="div_to_update"), but it could be other method also. 在下面的示例中,我使用Ajax.BeginForm来更新div(id =“div_to_update”),但它也可能是其他方法。

Important thing is OnSuccess which launches method below. 重要的是OnSuccess,它启动下面的方法。 That will update div content and executes all javascripts including your jquery validation. 这将更新div内容执行所有javascripts,包括你的jquery验证。 Originally I found this solution from Telerik forums. 最初我从Telerik论坛找到了这个解决方案。

<div id="div_to_update">
<% using (Ajax.BeginForm("Translations", new { Model.Id }, new AjaxOptions { OnSuccess = "updatePlaceholder", UpdateTargetId = "div_to_update", InsertionMode = InsertionMode.Replace }, new { id = "translationAjaxForm" }))
<% } %>

<script type="text/javascript">
    function updatePlaceholder(context) {
        // the HTML output of the partial view
        var html = context.get_data();

        // the DOM element representing the placeholder
        var placeholder = context.get_updateTarget();

        // use jQuery to update the placeholder. It will execute any JavaScript statements
        $(placeholder).html(html);

        // return false to prevent the automatic update of the placeholder
        return false;
    }
</script>
</div>

Please check out this link : Executing Dynamically Loaded JavaScript 请查看此链接: 执行动态加载的JavaScript
It contain fixes which suppose to execute javascript on the dynamically loaded (thru AJAX) partial views. 它包含修复,假设在动态加载(通过AJAX)部分视图上执行javascript。

what understand of your problem is that on partial update of the page the corresponding DOM elements are being re-inserted ie they are new and don have the required $.validate initialization. 你的问题的理解是,在部分更新页面时,重新插入相应的DOM元素,即它们是新的并且没有所需的$ .validate初始化。

I was thinking you could somehow use $.live/$.livequery to bind $.validate objects to those fields so after every partial page update the jquery code would re-initialize $.validate on to those fields. 我以为你可以以某种方式使用$ .live / $。livequery将$ .validate对象绑定到那些字段,因此在每次部分页面更新之后,jquery代码会将$ .validate重新初始化为这些字段。 May be you could use a css class to mark those DOM elements. 可能是您可以使用css类来标记这些DOM元素。

What I am suggesting is kind of late binding and use the newer events relating to DOM insertion. 我建议的是一种后期绑定并使用与DOM插入相关的新事件。

Hope this helps!! 希望这可以帮助!!

I've had similar problems loading javascript when I put content dinamically in the DOM. 当我将内容置于DOM中时,我在加载javascript方面遇到了类似的问题。 How are you inserting the content into the DOM? 你是如何将内容插入DOM的? There are some methods in jQuery that strip out the javascript when inserting try using this: jQuery中有一些方法在插入try时使用以下方法去除javascript:

$("#mydiv").html(newContent);

Hope this helps you! 希望这对你有所帮助!

Perhaps I am confused but could you just call the validate on the submit and not submit if fails? 也许我很困惑,但你可以在提交上调用验证,如果失败则不提交吗?

$(function() {
    $("form:first").validate( { .. options for validator .. });

    $("submit").click(function() {
        if(!$("form:first").valid()){ 
             return false;
        }
        // Submit form here
    });

});

I had this same issue and this is how I solved it. 我有同样的问题,这就是我解决它的方法。

Open up MicrosoftMvcJQueryValidation.js and make the following changes. 打开MicrosoftMvcJQueryValidation.js并进行以下更改。

Add this function 添加此功能

function __MVC_ApplyClientValidationMetadata() {
   var allFormOptions = window.mvcClientValidationMetadata;
   if (allFormOptions) {
      while (allFormOptions.length > 0) {
         var thisFormOptions = allFormOptions.pop();
         __MVC_EnableClientValidation(thisFormOptions);
       }
   }
}

Find the $(document).ready() and replace it with 找到$(document).ready()并替换它

$(document).ready(__MVC_ApplyClientValidationMetadata); 

Now just do the following 现在只需执行以下操作

If you use html() then just call __MVC_ApplyClientValidationMetadata after you load the html into the element. 如果你使用html(),那么在将html加载到元素后,只需调用__MVC_ApplyClientValidationMetadata。

$("#someDiv").html(responseHtml);
__MVC_ApplyClientValidationMetadata();

If you use load() then you have another problem. 如果你使用load(),那么你有另一个问题。 It's strips out all script tags. 它剥离了所有脚本标签。 So you have to do something like the following. 所以你必须做类似以下的事情。

$("#someDiv").load("/a/partialview/request" , function(response){
   var scripts = $(response).filter("script");
   for (var i = 0; i < scripts.length; i++) {
      //executes javascript
      $.globalEval(scripts[i].text);
   }
   __MVC_ApplyClientValidationMetadata();
});

One thing more thing. 还有一件事。 Make sure the forms you load using ajax have a unique id. 确保使用ajax加载的表单具有唯一ID。 By default, all forms get an id of form0. 默认情况下,所有表单都获得form0的id。

Part of the problem is the fact that the script included in the response is not executed. 部分问题在于响应中包含的脚本未执行。 In my case I had to work with a solution based on jcruz' solution, which selects the script from the certain ajax form: 在我的情况下,我不得不使用基于jcruz'解决方案的解决方案,该解决方案从特定的ajax形式中选择脚本:

var scripts = $('div#id_of_ajax_form>script');
for (var i = 0; i < scripts.length; i++) {
    //executes javascript
    $.globalEval(scripts[i].text);
}

The second part of the problem is the fact that the microsoft validation is being initialized after the is loaded by a call to Sys.Mvc.FormContext._Application_Load. 问题的第二部分是在通过调用Sys.Mvc.FormContext._Application_Load加载微软验证之后初始化的事实。 So after executing the needed script, containing the validation field specifications, I call the same function that is being called on document load: 因此,在执行包含验证字段规范的所需脚本之后,我调用在文档加载上调用的相同函数:

Sys.Mvc.FormContext._Application_Load();

hope this helps. 希望这可以帮助。 Any comments would be appreciated very much. 任何评论都会非常感激。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 ASP.NET MVC客户端验证与部分视图和Ajax - ASP.NET MVC client validation with partial views and Ajax 无法在使用jquery .load()方法加载的(asp.net mvc4)部分视图中打开kendoui下拉列表 - Can't open kendoui dropdown in a (asp.net mvc4) partial view loaded with jquery .load() method 如何在 Asp.Net MVC 中通过 jquery ajax 动态加载局部视图 - How to dynamically load partial view Via jquery ajax in Asp.Net MVC ASP.NET MVC 不触发 jQuery Ajax POST - ASP.NET MVC does not fire jQuery Ajax POST 通过Ajax加载的ASP.NET MVC3 EditorTemplates是否复制了jQuery? - ASP.NET MVC3 EditorTemplates Loaded via Ajax w/o duplicating jQuery? 如何在通过Ajax.ActionLink调用的动态加载的ASP.NET MVC局部视图上初始化jsTree - How can I initialize jsTree on a dynamically loaded ASP.NET MVC Partial View that is called via an Ajax.ActionLink asp.net mvc jquery Ajax部分页面更新问题 - asp.net mvc jquery Ajax partial page update issue ASP.NET MVC使用jQuery ajax渲染局部视图 - ASP.NET MVC rendering partial view with jQuery ajax 通过jquery $ .ajax发布时的ASP.NET MVC验证框架? - ASP.NET MVC Validation Framework when posting via jquery $.ajax? ASP.NET MVC Ajax JSON jQuery 不会将参数发送到“ActionResult” - ASP.NET MVC Ajax JSON jQuery won't send parameters to `ActionResult`
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM