What’s the best practice for using ASP.NET expressions inside an external Javascript file?
I’m using the ASP.NET MVC framework currently and need to do something similar to the following from within an external JS reference:
jQuery(document).ready (function () {
jQuery ("#element<%= Model.IdFromAThing %>").click (... blah ...
});
I could move this into the View, granted, but I’d like to keep it separate.
P.S.
One of the advantages of doing this is I can re-use the same JS file in many places, I don’t really want to repeat initialisation logic in each view (considering it’ll be identical).
I don’t think that’s possible unless you change your IIS to process .js files as ASP.NET.
External js files aren’t processed by ASP.NET, they are just sent to the web client. So there’s no way to use ASP.NET expressions inside of a .js file unless you mess with the IIS configuration and change it to process .js files as it would process an ASP.NET file.
On the other hand, you could rename your .js file as .aspx and then use that as your js src value. Then it would be processed using ASP.NET prior to sending it to the client. You just need to make sure there’s no automatically generated HTML code (just javascript) in the output.