Saturday, February 1, 2014

JavaScript "code behinds" in ASP.NET MVC applications.

At an ASP.NET MVC application, let's say you have a .cshtml view at /Views/Aardvark/AardvarkCountingWidget.cshtml. Let's also suppose that AardvarkCountingWidget.cshtml has a bunch of jQuery in it inside a script tag and you eventually wish to pull it out to a .js file. Well, I suppose that .js file could go at /Scripts/AardvarkCountingWidget.js, but what if it instead accompanied /Views/Aardvark/AardvarkCountingWidget.cshtml by living at /Views/Aardvark/AardvarkCountingWidget.js? In this convention a .cshtml file will have, if applicable, a .js "code behind" of the same name in the same folder. This is sort of like the code behinds of web forms... Mmmmm, maybe that's a stretch. Anyhow, this idea came from Joel Holder and it was going on at the AMD application I was a part of. That was an MVC3 project. /Views/Web.config prevents you from touching content inside of the Views folder in later versions of MVC save for using .cshtml views in the very different than usual way in Razor. So how do you allow access to .js files in the Views folder? Great question. I did it by removing everything between <httpHandlers> and </httpHandlers> and also between <handlers> and </handlers> at /Views/Web.config!

No comments:

Post a Comment