Mcloving
Mcloving

Reputation: 1410

ajax call triggering multiple times at once

The scenario is that Im basically trying to create 4 dropdowns, that repopulate when one is changed. Aka the filters are cascading, each other.

So I decided to put it in an Ajax call. And basically, it takes the params, decides what select lists should be returned. Then replaces the old 4 dropdowns with new dropdowns. (replaces current partial with new partial)

Except, for some reason I am getting it calling the controller once.. then twice.. then 4 times.. etc. As if the old ones are not being removed/ replaced. just hidden?..

Visually, I see what Id expect. THe dropdowns change selection options.

below is the code. (p.s. sorry if some variable names are typos, they have been changed for posting on 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);
    }

view:

    <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>

Upvotes: 3

Views: 3637

Answers (1)

Zach
Zach

Reputation: 3207

Move this outside your partial:

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

I also moved the change script outside the partial as well and changed it to handle dynamic content like so:

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

Upvotes: 5

Related Questions