Question

I have a page that contains a search bar, and on default it displays a list of items below. Each item is wrapped inside an ajaxform so that the user can update the quantity. The client side validation works perfectly fine on page load, and it requires a quantity.

As soon as the user clicks search, and the result of the partial is refreshed my whole validation breaks, and it doesn't display validation summary anymore.

I tried to add the validation back after refreshing the partial by calling $.validator.unobtrusive.parse($("#resultList")); but it doesn't seem to do anything.

Any solutions?

MainForm

<script>
function onSearchSucceeded() {
   $.validator.unobtrusive.parse($("#resultList"));
}

function onUpdateSucceeded() {
   $.validator.unobtrusive.parse($("#resultList"));
}

$(function () {

    $("#resultList :input[type=text]").blur(function () {
        $(this).closest("form").submit();
    });

)};

</script>


@using (Ajax.BeginForm("Search",
    null,
    new AjaxOptions
    {
        UpdateTargetId = "resultList",
        LoadingElementId = "searchLoader",
        OnSuccess = "onSearchSucceeded"
    },
    new
    {
        id = "searchForm"
    }
    ))
{
   @Html.TextBoxFor(m => m.query)
   <input type="submit" value="search" />
}


<div id="resultList">
   @Html.Partial("SearchResult", Model.Results)
</div>

Partial

@foreach (var item in Model) {
    using (Ajax.BeginForm("UpdateItem",
        new AjaxOptions {
            UpdateTargetId = "resultList",
            OnSuccess = "onUpdateSucceeded"
        },
        null,
        new{
            id = "form-" + item.Id
        }
     )){
       @Html.TextBoxFor(m => item.Quantity)
       @Html.ValidationSummary()
       // This form gets submitted through javascript after a blur on quantity textfield
     }
}
Was it helpful?

Solution

The onSearchSucceeded and onUpdateSucceeded functions seem correct to me. It is inside those functions that you are telling the jQuery unobtrusive framework that new DOM elements are present in the result div and need to be registered.

What troubled me is the following comment in your code:

// This form gets submitted through javascript after a blur on quantity textfield

Unfortunately you haven't exactly shown how this is done, but the following code worked fine for me:

$(document).on('blur', 'form[id^="form-"] input[name$="Quantity"]', function () {
    $(this).closest('form').submit();
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top