Search code examples
javascriptc#jqueryasp.net-mvcmodelstate

How to Reset the Values of the Controls in Partial View Upon Clicking on Browser's Back Button


I need a way to "reset" the dropdownlists in my partial view (search section) after re-displaying the whole page when the user clicks on the back button of the browser.

Index view contains the search partial view, search updates another section in the Index page, and when the user click on one of the results, the details page is shown. So far so good. However, if the user clicks on the browser's back button, the index page with the search partial view displayed again, but with the selected items in the dropdownlists. I need them to be reset.

I tried putting

[OutputCache(NoStore = true, Duration = 0)]

on top of the Index method, but it did not help.


Here's the partial view (in Index view/page)

enter image description here
Here is the controller code:

public ActionResult Search()
    {          
        var _citiesList = new SelectList((from c in repository.Cities select c), "CityID", "CityName");

        var searchViewModel = new ServiceProviderViewModel.SearchModel
        {
            CitiesList = _citiesList
        };

        return PartialView("_SearchSP", searchViewModel);          
    }

    [HttpPost]
    public ActionResult Search(ServiceProviderViewModel.SearchModel searchViewModel)
    {
        if (ModelState.IsValid)
        {
            var _serviceProviders = repository.ServiceProviders.
                Where(sp => sp.ServiceTypes.Select(t => t.ID).Contains((int)searchViewModel.ServiceType))
                .Where(sp => sp.DistrictID == searchViewModel.selectedDistrictID);

            return PartialView("_SearchResults", _serviceProviders);
        }
        else
        {
            return PartialView("_SearchSP", searchViewModel);
        }
    }


    public ActionResult GetDistrictsOfTheCity(int cityId)
    {
        var districts = new SelectList(repository.Districts.Where(d => d.CityID == cityId), "DistrictID", "DistrictName");

        return Json(districts, JsonRequestBehavior.AllowGet);
    }

Solution

  • Duplicate With

    Modern browsers implement something known as back-forward cache (BFCache). When you hit back/forward button the actual page is not reloaded (and the scripts are never re-run).

    If you have to do something in case of user hitting back/forward keys -- listen for BFCache pageshow and pagehide events.

    A pseudo jQuery example:

    $(window).bind("pageshow", function() {
      // update hidden input field
    });
    

    See more details for Gecko and WebKit implementations.