Search code examples
javascriptjqueryajaxasp.net-mvcunobtrusive-validation

Can I use ValidationSummary on a PartialView returned by ajax call?


I have an asp.net MVC application which uses jquery unobtrusive validation. I would like to use the Html.ValidationSummary on a form that is generated as described below.

Is there any hack or workaround I can use to get Html.ValidationSummary to work on forms that are generated via an ajax call that fetches and displays a partial view?

I use ajax to call a Controller action which returns a partial view. I then set the html of a div to the ajax call result. The ajax call looks like this:

$.ajax({
            type: "GET",
            url: '/MyDomain/GetPartialView?myId=' + myId,
            cache: false,
            dataType: "html",
            success: function (responseText) {
                $tab.html(responseText);
                $tab.find('form').validate();
            }
   });

And the Controller Action looks like this:

public ActionResult GetPartialView(long myId)
{
    model = GetModel(myId);
    return PartialView("_MyPartialView", model);
}

The PartialView is a plain old *.cshtml page that generates a form, like below, and on that form I have a (non-functioning) ValidationSummary along with a bunch of inputs. Is there any way I can make it function? Right now jquery unobtrusive validation works, but it shows the error message next to each invalid input. I would like to have the page display error messages in the ValidationSummary instead.

@using (Html.BeginForm("MyAction", "MyController", FormMethod.Post,     new { enctype = "multipart/form-data" }))
{
    <span id="validation-errors" class="validation-summary-errors">@Html.ValidationSummary(false, "Submit was unsuccessful. Please correct the errors and try again.")</span>

    <div>@Html.EditorFor(m => m.MyField)</div>
}

Solution

  • @StephenMuecke, if you want to post your comment as an answer I'll use that and delete this one. The answer as stated by @StephenMuecke is to reparse the validator. My ajax call now looks like this, the 2 added lines of code fixes the issue:

    $.ajax({
            type: "GET",
            url: '/MyDomain/GetPartialView?myId=' + myId,
            cache: false,
            dataType: "html",
            success: function (responseText) {
                $tab.html(responseText);
                var $form = $tab.find('form');
                $form.data('validator', null);
                $.validator.unobtrusive.parse($form);
            }
       });