Note that there are some explanatory texts on larger screens.

plurals
  1. POunobtrusive validation not working with dynamic content
    primarykey
    data
    text
    <p>I'm having problems trying to get the unobtrusive jquery validation to work with a partial view that is loaded dynamically through an AJAX call.</p> <p>I've been spending days trying to get this code to work with no luck.</p> <p>Here's the View:</p> <pre><code>@model MvcApplication2.Models.test @using (Html.BeginForm()) { @Html.ValidationSummary(true); &lt;div id="res"&gt;&lt;/div&gt; &lt;input id="submit" type="submit" value="submit" /&gt; } </code></pre> <p>The Partial View:</p> <pre><code>@model MvcApplication2.Models.test @Html.TextAreaFor(m =&gt; m.MyProperty); @Html.ValidationMessageFor(m =&gt; m.MyProperty); &lt;script type="text/javascript" &gt; $.validator.unobtrusive.parse(document); &lt;/script&gt; </code></pre> <p>The Model:</p> <pre><code> public class test { [Required(ErrorMessage= "required field")] public int MyProperty { get; set; } } </code></pre> <p>The Controller:</p> <pre><code> public ActionResult GetView() { return PartialView("Test"); } </code></pre> <p>and finally, the javascript:</p> <pre><code>$(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; } }); </code></pre> <p>The validation does not work. Even if I don't fill any information in the texbox, the submit event shows the alert ('valid'). </p> <p>However, if instead of loading dynamically the view, I use <code>@Html.Partial("test", Model)</code> to render the partial View in the main View (and I don't do the AJAX call), then the validation works just fine.</p> <p>This is probably because if I load the content dynamically, the controls don't exist in the DOM yet. But I do a call to <code>$.validator.unobtrusive.parse($("#res"));</code> which should be enough to let the validator about the newly loaded controls...</p> <p>Can anyone help ? </p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload