views:

173

answers:

2

Hi,

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).

+2  A: 

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.

Jim W
Yeah, I knew that was the case for IIS, I was hoping there may be a way to tell IIS to pre-process the JS file via config - perhaps there's already a HttpModule or HttpHandler that can do it?
Kieron
+1  A: 

Jim is correct, to have a JS file include dynamic content you would need the ASP.NET engine to parse/process these.

Another idea is to slightly refactor what you're doing. Create your JS files to accept (dynamic) parameters from your dynamic page, which can be injected. For example, your example might be rewritten as follows:

In your static JS file:

function setItUp(idFromAThing) {
    jQuery(document).ready (function () {
        jQuery ("#element" + idFromAThing).click (... blah ...
    });
}

And in your ASP.NET View:

<script type="text/javascript" src="whatever.js"> </script>
<script type="text/javascript">
setItUp(<%= Model.IdFromAThing %>);
</script>

Good luck!

Funka
P.S. if you have more than one variable to pass in, you could use a nice neat JSON structure as these params...
Funka