Trouble getting unobtrusive validation working with mvc 3 on jquery ajax post
Asked Answered
K

1

13

I have having a lot of trouble getting validation to work on MVC3. It works fine when I just load the page directly, but it does not validate when I use jquery AJAX POST:

This form is loaded using $('#modal-dialog').load('/DartsMVC/Restaurant/Edit/13'), This is the rendered HTML:

<form action="/DartsMVC/Restaurant/Edit/13" method="post">
    <fieldset>
        <legend>Restaurant</legend>

        <input data-val="true" data-val-number="The field RestaurantID must be a number." data-val-required="The RestaurantID field is required." id="RestaurantID" name="RestaurantID" type="hidden" value="13">

        <div class="editor-label">
            <label for="Name">Name</label>
        </div>
        <div class="editor-field">
            <input class="text-box single-line" data-val="true" data-val-required="The Name field is required." id="Name" name="Name" type="text" value="furaibo">
            <span class="field-validation-valid" data-valmsg-for="Name" data-valmsg-replace="true"></span>
        </div>

        <p>
            <input type="submit" value="Save" class="ui-button ui-widget ui-state-default ui-corner-all" role="button" aria-disabled="false">
        </p>
    </fieldset>
</form>

AJAX POST is used by intercepting the form/submit. The modal dialog pops up and closes itself after the post completes. I would like to validate the form before sending the post:

// force change the submit data to an ajax POST (usually 'save', 'delete' button)
$('#modal-dialog').delegate('form', 'submit', function (e) {
    e.preventDefault();
    var form = $(this);
    form.validate(); // does nothing
    if (form.valid()) {
        $.ajax({
            url: form.attr('action'),
            type: "POST",
            data: form.serialize(),
            success: function (data) {
                $('#modal-dialog').dialog('close');
            },
            error: function (jqXhr, textStatus, errorThrown) {
                alert("Error '" + jqXhr.status + "' (textStatus: '" + textStatus + "', errorThrown: '" + errorThrown + "')");
            }
        });
    }
});

Did I break something by doing this? .valid() always returns true.

My web.config has:

  <appSettings>
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  </appSettings>

My page source has:

<link href="/DartsMVC/Content/themes/cupertino/jquery-ui-1.8.14.custom.css" rel="stylesheet" type="text/css">

<script src="/DartsMVC/Scripts/modernizr-1.7.min.js" type="text/javascript"></script>
<script src="/DartsMVC/Scripts/jquery-1.5.1.min.js" type="text/javascript"></script>
<script src="/DartsMVC/Scripts/jquery-ui-1.8.14.custom.min.js" type="text/javascript"></script>

<script src="/DartsMVC/Scripts/jquery.unobtrusive-ajax.js" type="text/javascript"></script>
<script src="/DartsMVC/Scripts/jquery.validate.js" type="text/javascript"></script>
<script src="/DartsMVC/Scripts/jquery.validate.unobtrusive.js" type="text/javascript"></script>

And my model has:

    [Required]
    public string Name { get; set; }

After more research, I think it may have something to do with dynamic controls:

Kenwrick answered 10/8, 2011 at 1:49 Comment(0)
K
27

Solved

Calling $.validator.unobtrusive.parse($('form')) did the trick. I guess the validator needs to be recreated for dynamic content

Kenwrick answered 11/8, 2011 at 0:38 Comment(3)
Thanks! I had this figured out a while ago, but forogt and had quite a hard time finding the solution again.Algeria
@Algeria Where do you call in your code the $.validator code from above. I might have a similar problem :/Michael
@Elisa, I ended up creating an AddRemoveValidator function for reinitializing unobtrusive validation: //reinitialize unobtrusive validation addValidationToForm: function(formToAdd) { jQuery.each(formToAdd, function(i, form) { $(form).removeData("validator"); $.validator.unobtrusive.parse(form); }); }, addValidationToFormRemoveFromOthers: function(formToAdd, formsToRemoveFrom) { for(var from in formsToRemoveFrom) { $(from).removeData("validator"); } global.addValidationToForm(formToAdd); }Algeria

© 2022 - 2024 — McMap. All rights reserved.