0

I have a page which has a list of filters based on which I want to reload its main content. I am trying to do this by using window.history.pushState (HTML5) to keep updating the url's query string everytime the user changes the filters.

This works for the first filter and does not work when I added another filter after the first one.

Here is my code. The function FilteredByHospital() is called whenever there are changes in the checklist of hospitals.

var filters = new Object();
filters.Hospitals = new Array();
function FilteredByHospital(hospitalId) {
    debugger;
    var obj = { hospitalId: hospitalId };
    filters.Hospitals.push(obj);
    var isFirstFilter = window.location.href.indexOf('?') == -1;
    var currentUrl = window.location.href;
    if (isFirstFilter) {
        window.history.pushState(filters, "Filter_" + hospitalId, currentUrl + "?hospitalIds[0]=" + hospitalId);
    } else {
        window.history.pushState((filters, "Filter_" + hospitalId, currentUrl + "&hospitalIds[" + (filters.Hospitals.length - 1) + "]=" + hospitalId));
    }
}

The checklist of hospitals (Razor)

<div class="FilterBox">
    @foreach (var hospital in Model.Hospitals)
    {
        <input style="cursor: pointer;" type="checkbox" name="HospitalId" value="@(hospital.Value)" onchange="FilteredByHospital('@(hospital.Value)')"/><span>@(hospital.Text)</span><br/>
    }
</div>

When I select one of the hospital checkboxes, the URL correctly changes to http://localhost:56195/ApplicationHealthCheck/Index?hospitalIds[0]=139961407289011 and my Controller's action is hit.

When I do this again for another checkbox, the URL remains the same and the action is hit again with only the first hospital ID. Instead, the URL should change to http://localhost:56195/ApplicationHealthCheck/Index?hospitalIds[0]=139961407289011&hospitalIds[1]=26419769705609.

What am I doing wrong?

mridula
  • 3,203
  • 3
  • 32
  • 55

2 Answers2

0

There was an extra pair of brackets in the second pushState call.

Replaced

window.history.pushState((filters, "Filter_" + hospitalId, currentUrl + "&hospitalIds[" + (filters.Hospitals.length - 1) + "]=" + hospitalId));

with

window.history.pushState(filters, "Filter_" + hospitalId, currentUrl + "&hospitalIds[" + (filters.Hospitals.length - 1) + "]=" + hospitalId);
mridula
  • 3,203
  • 3
  • 32
  • 55
0

Take a look carefully at this line of your code:

window.history.pushState((filters, "Filter_" + hospitalId, currentUrl + "&hospitalIds[" + (filters.Hospitals.length - 1) + "]=" + hospitalId));

Did you notice the double parentheses at pushState((?

In this line, you are not calling pushState with three arguments. You are applying the comma operator to your arguments, and then passing the result to pushState. Your code gets evaluted to

window.history.pushState(currentUrl + "&hospitalIds[" + (filters.Hospitals.length - 1) + "]=" + hospitalId);

Which is, obviously, is not right.

izstas
  • 5,004
  • 3
  • 42
  • 56