6

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 :(

1
  • Post the code you have tried and we'll see if and/or where you are going wrong. Commented Apr 3, 2010 at 17:24

2 Answers 2

15

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.

Sign up to request clarification or add additional context in comments.

2 Comments

except the weird case where you want to add security validation to returned files that are dependent on a user's authentication profile / membership IDs. In that case convention can suck it.
If you are suggesting what I think you are suggesting, don't forget, you can initialise javascript variables/properties using your model in the served page and then check for their existence/value in the centrally served javascript module. You could also make the centrally serviced scripts directory into a controller-based solution and modify the values you need there. There are lots of solutions/approaches available to you that would be cleaner than javascript files peppered around your View hierarchy.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.