To do this, your JavaScript file must be preprocessed on the server side. Essentially, it was supposed to be an ASP.NET view for a certain type, and script tags that reference a file would essentially refer to a controller action that responds to that view.
It is like a can of worms that you do not want to open.
Since JavaScript is client-side, why not just set a value for some element on the client side and associate JavaScript with it. This may be an extra step of indirection, but it sounds much less than a headache than creating a JavaScript view.
Something like that:
<script type="text/javascript"> var someValue = @ViewBag.someValue </script>
An external JavaScript file can then reference the JavaScript variable someValue within the scope of this document.
Or even:
<input type="hidden" id="someValue" value="@ViewBag.someValue" />
Then you can access this hidden input.
Unless you come up with some really smooth way to make your JavaScript file usable as a presentation. This is certainly doable, and I can't readily think of any problems you would have (other than the really ugly view code, since the view mechanism will be very confused as to what JavaScript is and what Razor is .. so expect a ton <text> markup), so if you find a smooth way to do this, it will be pretty cool, although perhaps not intuitive for someone who needs code support later.
David Apr 30 '12 at 19:59 2012-04-30 19:59
source share