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?