- Since the application is still in development I don't have to worry about the browser caching JS files if the code is in the View.
- I often have Url.Action and other snippets of Razor mixed in with my javascript.
I was just getting to the point where I was ready to move this code to its own .js file but I was worried about how to deal with the Razor that was mixed in. Thanks to John Katsiotis's (aka djsolid) RazorJS project I now have a solution!
Installation is easy, just use Nuget to add RazorJS to your solution in Visual Studio. The command line to do is:
Install-Package RazorJS
By default @Url.Action will not work and you'll get the error:
To get it to work add the following at the top of your javascript file.
error CS0103: The name 'Url' does not exist in the current context
To get it to work add the following at the top of your javascript file.
@{ var Url = new System.Web.Mvc.UrlHelper(System.Web.HttpContext.Current.Request.RequestContext); }
If you run into other errors you should be able to use similar workarounds. If you do use other workarounds, let me know and I can add them to this post.
UPDATE: In version 0.4.2 you no longer need this work around for the UrlHelper. Thanks to John for adding this so fast!