up vote 0 down vote favorite

Hi all fellow programmer

I'd like to have a separate js file for each MVC set I have in my application

/Controllers/
    -TestController.cs
/Models/
/Views/
    /Test/
        -Index.aspx
        -script.js

And I'd like to include the js in the Index.aspx by

<script type="text/javascript" src="<%=UriHelper.GetBaseUrl()%>/Test/Js"></script>

Or to put it easier, when I call http://localhost/Test/Js in the browser, it will show me the script.js file

How to write the Action in the Controller? I know that this must be done with return File method, but I haven't successfully create the method :(

link|flag
Post the code you have tried and we'll see if and/or where you are going wrong. – Lazarus Apr 3 at 17:24

2 Answers

up vote 4 down vote accepted

How about:

    public FileContentResult Js()
    {
        return File(System.IO.File.ReadAllBytes(Server.MapPath("/Test/script.js")), "text/javascript");
    }

I will add that you really should have your scripts under your Content folder as MVC is all about convention above configuration and by trying to place your scripts with your views you are breaking convention.

link|flag
1  
+1 for convention.. That is what MVC is all about – Flexo Apr 3 at 17:38
+1 for a great nickname! ;) – Lazarus Apr 3 at 17:43
up vote 1 down vote

Two options:

  • Return the javascript as a string using the Javascript ActionResult
  • Return the javascript file as a downloadable file using the File download ActionResult

HTH.

link|flag

Your Answer

 
or
never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.