Monday, July 16, 2012

How to force to update JavaScript and CSS files after deploying new version of ASP.NET MVC application.

Usually after each deployment my ASP.NET MVC (Razor view) site I have a little mess with cached JavaScript and CSS files. Sometimes user's browsers show unappropriated view or some client functionality doesn't work.
Yeah, it is very easy to fix - just clear browser cache or reload JavaScript and CSS files (press CTRL+F5). But I want user to avoid this annoying action moreover not all users are so familiar with PC to know this trick.
My friend Mykhailo found nice solution for this. If I add parameter to JavaScript's url and will change parameter's value after each deployment. Browser will recognize it as other script and will update file.
So now I should add something like "?v=xxxx" to all links of CSS and JavaScript files in my project and keep in mind it for future links. Looks not really smart solution doesn't it?
First of all I want to say that I set JavaScript and CSS files in "Razor" style. For instance:

Wednesday, June 13, 2012

Route of executing in Controller of ASP.NET MVC

Base classes of controller is ASP.NET MVC have number of methods for initialization before your code runs in an action. Lets review them.

  • First of all about constructor. You can't do a lot in it because most of properties aren't initialized yet and you will get NullReferenceException if try to use them.
  • Execute is inherited from IController interface and manages all other initialization methods. Usually you have to avoid override it.
  • Initialize sets ControllerContext. You should to override it if you need to set culture so on.
  • ExecuteCore is called to process request and responsible for loading TempData.
  • If I want to predefine some information (grab data from Session and so on) You should use OnActionExecuting. This methods is called just before executing your action method.
  • And finally you should use OnActionExecuted for any finalization after executing your code. 

PS: During preparing for this post I've used ILSpy. It is excellent free substitute for .NET Reflector (it is payment tool now).