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>

Answers


If you don't refresh the containing form you may also need the following:

success: function (data) {
    var holder = $('#newItemHolder');
    // get the containing form
    var form = $(holder).closest('form');

    holder.html(data);
    form.removeData('validator');
    form.removeData('unobtrusiveValidation');
    jQuery.validator.unobtrusive.parse(form);
}

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.


Need Your Help

Windows 8 metro apps array

windows-8 microsoft-metro windows-8.1 windows-rt

I need to switch between metro apps backwards and forwards. Is there a way to get an array of metro apps or the number of metro apps running?

WinSCP login issue with sudo

sftp openssh tty winscp

I am trying to login using WinSCP using correct username and password.