Ajax call calls multiple times in a row

The scenario is that I'm basically trying to create 4 dropdowns that populate on change. Aka filters cascade each other.

So I decided to put it in the Ajax call. And basically, it takes parameters, decides which picklists should be returned. Then replaces the old 4 dropdowns with new dropdowns. (replaces the current partial with a new partial)

Except that for some reason I get it called by the controller once .. then twice .. then 4 times, etc. As if the old ones are not deleted / replaced. just hidden? ..

Visually, I can see what Eid is waiting for. The drop-down list changes the selection options.

below is the code. (ps sorry if some of the variable names are typos, they were changed for posting here)

Controller:

   public class Filter
    {
        public IEnumerable<SelectListItem> List1;
        public IEnumerable<SelectListItem> List2;
        public IEnumerable<SelectListItem> List3;
        public IEnumerable<SelectListItem> List4;
    }

    public ActionResult GlobalFilter(String l1, String l2, String l3, String l4)
    {
        Filter filter = new Filter();

        filter.List1 = ...selectList

        filter.List2 = ...selectList

        filter.List3 = ...selectList

        filter.List4 = ...selectList

        return PartialView(filter);
    }

      

:

    <div id="filterPartial">

        @Html.Action("GlobalFilter", "Header")
    </div>

      

partial view:

@model ns.Controllers.HeaderController.Filter

<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>

@using (Ajax.BeginForm("GlobalFilter", "Header", new AjaxOptions { UpdateTargetId = "filterPartial" }))
{ 

    @Html.DropDownList("l1", Model.List1, new { })
     @Html.DropDownList("l2", Model.List2, new { })

     @Html.DropDownList("l3", Model.List3, new { })
      @Html.DropDownList("l4", Model.List4, new { })

}
<script type="text/javascript">
    $('#l1').change(function () {
        $(this).parents('form').submit();
    });
</script>

      

+3


source to share


1 answer


Move this outside of the partial:

<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>

      



I also moved the change script outside of the partial and changed it to handle dynamic content like this:

<script type="text/javascript">
    $('#filterPartial').on('change', '#l1', function () {
        $(this).closest('form').submit();
    });
</script>

      

+5


source







All Articles