Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. The partial view is loaded via ajax into a modal dialog using the url (almost like 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.

like image 900
William Hurst Avatar asked Jul 30 '10 08:07

William Hurst


1 Answers

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.

Important thing is OnSuccess which launches method below. That will update div content and executes all javascripts including your jquery validation. Originally I found this solution from Telerik forums.

<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>
like image 199
Tx3 Avatar answered Oct 20 '22 07:10

Tx3