Willy
Willy

Reputation: 10638

How to import a js file into view in mvc

I have below view with scripts at the end:

View:

(...)

// here my html items etc...

(...)

<script type="text/javascript" src="~/Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript">

 // here all my stuff
      function sample1()
      {
      }

      function sample2()
      {
      }

      function sample3()
      {
      }

</script>

so what I want is to put all the code within into a js file and place it under /Scripts folder in mvc 4 so how to do this? In this script I refer to items in the view.

so after this change I have:

View:

(...)

// here my html items etc...

(...)

<script type="text/javascript" src="@Url.Content("~/Scripts/jquery-1.10.2.min.js)"></script>
<script type="text/javascript" src="@Url.Content("~/Scripts/Customs/MyCustomJsFile.js")">
</script>

Javascript file (under /Scripts folder):

MyCustomJsFile.js:

      function sample1()
      {
      }

      function sample2()
      {
      }

      function sample3()
      {
      }

in runtime I am getting an error saying synatx error in MyCustomJsFile.js in the ie debug console so I click the error and first line is shown as error:

but my js file has not any script line....

Upvotes: 0

Views: 3026

Answers (1)

asymptoticFault
asymptoticFault

Reputation: 4529

The only thing that should be in your MyCustomScript.js file is the code you had between the <script> tags, not the tags themselves nor the <script> tag to include jQuery. jQuery should be included in your view on in your Layout and it should be included before your file.

For example, your view:

<script type="text/javascript" src='@Url.Content("~/Scripts/jquery-1.10.2.min.js")'></script>
<script type="text/javascript" src='@Url.Content("~/Scripts/Tests/MyCustomScript.js")'></script>

Your MyCustomScript.js file:

// here all my stuff

jQuery should really be included on your Layout since you will likely be using it on most, if not all, of your Views.

Upvotes: 1

Related Questions