1

First, I read this question already but it doesn't answer to my issue.

Let's say I have a model:

public class MyModel {
   [Required]
   public string Email { get; set; }

   public string Text { get; set; }
}

and a partial view _MyForm.cshtml :

@model MyModel
<form>
   @Html.LabelFor(m=>m.Email)
   @Html.TextBoxFor(m=>m.Email)
   <br />
   @Html.LabelFor(m=>m.Text)
   @Html.TextBoxFor(m=>m.Text)
  <br/>
   <input type="submit" value="submit" />
</form>

An action which returns that partial view

public PartialViewResult GetView(){
   return PartialView("_MyForm", new MyModel());
}

and I call that view via ajax

$.ajax({
   url: "/Home/GetView",
   dataType: "html",
   success: function(html) {
       $("#aDiv").html(html);

       $("#aDiv :submit").on("click", function (){
           $(this).closest("form").validate({
              submitHandler: function (){  alert('valid'); }
           });
       }); 
   }
});

The problem, is I don't fill the e-mail field, alert dialog is displayed instead to make email (which is required) field with red border.

If I don't call that view using ajax, and I use Html.RenderPartial('_MyForm', new MyModel()) inside a view then it works.

With other words, if that partial view is rendered normally (by calling RenderPartial) then validation works, if it is rendered through ajax then validation is not working.

Why ? I have no error, I log the html parameter from success function, seems to be ok.

Community
  • 1
  • 1
Snake Eyes
  • 16,287
  • 34
  • 113
  • 221

1 Answers1

8

This is quite common, when the view is loaded normally, the inputs are present in the dom when the validator is bound up.

When you load in via ajax, they aren't, so they don't participate in the validation cycle.

you can get them to participate by calling this code in your ajax success handler

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

That will add the controls to the validation cycle

Slicksim
  • 7,054
  • 28
  • 32
  • This is the solution! I forgot that my view is dinamically appended to DOM and validator cannot reach my dynamic form. – Snake Eyes Feb 20 '15 at 09:51