I'm having trouble trying to get an unobtrusive jquery validation to work with a partial view that is dynamically loaded using an AJAX call.
I spent days trying to get this code to work without any luck.
Here View:
@model MvcApplication2.Models.test @using (Html.BeginForm()) { @Html.ValidationSummary(true); <div id="res"></div> <input id="submit" type="submit" value="submit" /> }
Partial view:
@model MvcApplication2.Models.test @Html.TextAreaFor(m => m.MyProperty); @Html.ValidationMessageFor(m => m.MyProperty); <script type="text/javascript" > $.validator.unobtrusive.parse(document); </script>
Model:
public class test { [Required(ErrorMessage= "required field")] public int MyProperty { get; set; } }
Controller:
public ActionResult GetView() { return PartialView("Test"); }
and finally javascript:
$(doument).ready(function () { $.ajax({ url: '/test/getview', success: function (res) { $("#res").html(res); $.validator.unobtrusive.parse($("#res")); } }); $("#submit").click(function () { if ($("form").valid()) { alert('valid'); return true; } else { alert('not valid'); return false; } });
Validation does not work. Even if I don't fill in any information in texbox, the submit event shows a warning ("valid").
However, if instead of dynamically presenting the view, I use @Html.Partial("test", Model) to render the partial view in the main view (and I do not make an AJAX call), then the check works just fine.
This is probably due to the fact that if I load content dynamically, the controls do not yet exist in the DOM. But I'm calling $.validator.unobtrusive.parse($("#res")); which should be sufficient to allow the validator about recently loaded controls ...
Can anyone help?
asp.net-mvc-4 unobtrusive-validation
Sam Feb 15 '13 at 20:11 2013-02-15 20:11
source share