I have a .csHtml
-razor file with a javascript function that uses the @Url.Content
C# function inside for the ajax URL.
I want to move that function to a .js
file referenced from my view.
The problem is that javascript doesn't "know" the @
symbol and doesn't parse the the C# code.
Is there a way to reference .js
files from view with "@" symbol?
One way to tackle the problem is:
Adding a partial view with the javascript functions to the view.
This way you can use the
@
symbol and all yourjavascript
functions are separated from the view.Probably this is not the right approach. Considering separation of concerns. You should have a
data injector
on yourJavaScript
class and which is in most cases data isJSON
.Create a JS file in your
script
folder and add this reference to yourView
Now, consider a
JavaScript
literal class in youryourJsFile.js
:Also declare a class
Now, from your
Action
do this:And from your view:
You have two options:
For example:
And then in your view, set it:
UPDATE
You might wonder none is any good because of coupling, well it is true, you are coupling js and view. That is why scripts must be oblivious to the location they are running in so it is a symptom of non-optimum organization of files.
Anyway there is a third option to create a view engine and run the js files against the razor and send the results back. This is cleaner but much slower so not recommended either.
I think you are stuck with having to put that JS code in the View. The Razor parser, as far as I know, won't look at .js files, thus anything you have which uses
@
won't work. PLus, as you have spotted, Javascript itself does not like this@
character hanging around for no reason, other then, say, in a string.I recently blogged about this topic: Generating External JavaScript Files Using Partial Razor Views.
My solution is to use a custom attribute (
ExternalJavaScriptFileAttribute
) which renders a partial Razor view as is and then returns it without the surrounding<script>
tags. That makes it a valid external JavaScript file.In order to get the
@
variable into your .js file you'll have to use a global variable and set the value of that variable from the mvc view that is making use of that .js file.JavaScript file:
MVC View file:
Just be sure that any calls to your function happen AFTER the value has been set by the view.