Tuesday, January 14, 2014

RazorJS: The solution to using Razor in external JavaScript Files

If you are like me, I prefer to separate all JavaScript from the Views or Webpages. The difficulty in doing this is the lack of a method to use Razor Syntax to inject more fault tolerant urls, data and other Razor goodies. Yes, it can be achieved with out Razor by declaring the variables in a small JavaScript but I want complete separation not partial.

I did a little digging and found that there is a project called RazorJS. This project does exactly what I am looking to do with a few limitations. This project allows you to use the full Razor syntax with in the JavaScript and allows data models to be passed in so it can be references as part of the Razor. The limitations that I have found at the current moment is the lack of support for the ViewBag, ViewData, and TempData to be referenced in the Model. The solution is to add these to the strongly typed view model or as a dictionary.

For example of how to implement RazorJS and documentation refer to http://john.katsiotis.com/blog/razorjs---write-razor-inside-your-javascript-files

To install RazorJS via Nuget use Install-Package RazorJS. Details on the Nuget package can be found at http://www.nuget.org/packages/RazorJS/

*** All Content is provided As Is ***