0

I have cascading dropdowns to bring the list of contacts for the selected company. Request for contacts of the selected company is made as follows using JSON request.

On the view:

$('#companyId').change(function () {
        var selectedCompany = $(this).val();
        if (selectedCompany != null && selectedCompany != '') {

            $.getJSON('@Url.Action("Contacts")', { id: selectedCompany }, 
                           function (Contacts) {

                        var contactSelect = $('#contactId');
                        contactSelect.empty();
                        $.each(Contacts, function (index, contact) {
                        contactSelect.append($('<option/>', {
                        value: contact.value,
                        text: contact.text
                    }));
                });
            });
        }
    });

Controller:

public ActionResult Contacts(int id)
    {

        return Json(

            db.Contacts.Where(x=>x.deleted==false).
            Select(c => new { value = c.contactId, text = c.contactName, c.companyId }).
            Where(t => (int)t.companyId == id).OrderBy(x=>x.text),
            JsonRequestBehavior.AllowGet
        );
    }

This is working good. However, this server side code is executed only for the first time for any selected company (in the first dropdown). ie. if I select ComanyA then CompanyB and again CompanyA, it does not bring the contact list from the server instead populated from cache. Therefore the new contacts are not populated as expected.

Any help would be great !

Kaf
  • 33,101
  • 7
  • 58
  • 78

2 Answers2

1

You need to add a random number to the request so the browser believes its a separate call everytime. You can change the code to:

$.getJSON('@Url.Action("Contacts")', { id: selectedCompany, n : Math.random() }, 
                           function (Contacts) {

                        var contactSelect = $('#contactId');
                        contactSelect.empty();
                        $.each(Contacts, function (index, contact) {
                        contactSelect.append($('<option/>', {
                        value: contact.value,
                        text: contact.text
                    }));
                });
            });
Wiz
  • 477
  • 5
  • 17
1

That's IE caching issue, there are few ways to solve it on client-side or on server-side. Check this question for details and recipes. $.getJSON returning cached data in IE8

Community
  • 1
  • 1
dimuch
  • 12,728
  • 2
  • 39
  • 23