ASP.Net MVC Disable Cache To Keep Ajax Working OK
After coming back to my ASP.Net MVC project where I was using the Html.DropDownList scheme I had written about earlier on this blog, I cam across a bug where my dialog containing the dropdownlist wouldn’t show the correct selected item. I could choose a new selected item and submit the form back to the server OK but on reloading the dialog, the first item in the dropdown was always selected. My initial though was that my example code was incorrect and that I needed to start hunting again to find out how dropdownlists really work. However, while debugging, I noticed that the controller action that was returning the partial view for the Jquery dialog containing the dropdownlist seemed to only run once. I had placed a breakpoint in the action and noticed that the breakpoint was only hit when the dialog was loaded for the first time.
I was loading the view into containing the dropdownlist into a Jquery dialog using a load call like this:
A little research found out that these type of Ajax calls can be cached by browsers. This explained why the load resulted in my action being called once but not a second time – since the IE browser had cached the response.
To get the partial view to load reliably, I ad to disable the cache. To do this I put an OutputCache attribute on the controller action as follows:
[OutputCache(Duration = 0, VaryByParam = "*")] [HttpGet] public ActionResult CreateCustomer()
This attribute could be applied at the controller level in order to disable caching for the entire controller:
[OutputCache(Duration = 0, VaryByParam = "*")] public class CustomersController : Controller
but for the specific problem I had, it works fine just being applied to my specific controller action.