Search code examples
jqueryasp.net-mvc-3data-annotationsunobtrusive-validationclient-side-validation

Dynamically loaded content in MVC3 Partial view with client validation and controls with the same name


I am loading a primary view that initially renders a Partial view with a model that has a required field. As you would expect client validation works on that initial Partial but when I render the same Partial view dynamically using AJAX the client validation fails to recognize the dynamically added fields as unique.

I'm not surprised by this because after all they have the same name, id and validation data-dash attributes but is there a way to get the client validation messages to recognize each field separately without having to manually check and apply client validation in script?

Primary View:

@{Html.EnableClientValidation(); }
@{using (Html.BeginForm()){
    @Html.Partial("_WorkItem")
    <div id="newItemHolder">

    </div>

    <div id="addItem">Add Item</div>
}}

<script type="text/javascript">
  $(document).ready(function () {
    $("#addItem").click(function () {
        $.ajax({
            type: "POST",
            data: {},
            url: "Controller/NewItem",
            success: function (data) {
                //inject partial views content to newItemHolder
                jQuery.validator.unobtrusive.parse($("#newItemHolder"));
            }
        });
    });
  });
</script>

Solution

  • I found a way to fix this and in case anyone else has this same scenario/issue I'll include the resolution that I came up with. If anyone has accomplished the goal of validating each partial using client side validation via the data annotations I would definitely be interested to hear how you did it too!

    What I did was to put each partial into a form, that way the validation has unique names on the fields in each form then with some trigger, and eventually with the form submit I called the following.

    $('form').each(function () {
        $(this).validate().form();
    });
    

    The result is that each field that is required is validated on it's own and when providing a value for one required field it does not cause the client side validation to succeed for all controls that share the same name.