2

In internet I found many samples of code in JS like this:

window.location.href = "@Url.Action('Index', 'Home')";

People use HTML helpers in javascript code, for example see that. But when I want to do it I get a simple string:

http://localhost:28832/@Url.Action('Index',%20'Home')

Why are my HTML helpers not being processed?

Community
  • 1
  • 1

1 Answers1

3

The razor syntax work on the view. If your JS code in embedded inside the view it will work. Don't expect it to work if you have the JS code in an external file.

If you think about how the js files are served razor engine never process them, they are just resources. I don't know if there is a way of adding js support to the razor engine.

I use this workaround: When I need some dynamic (razor) content on a JS file what I do is declare a function and put the content as an argument of the function. Then I call the function from the view file and pass the razor statement as parameter. In your case this could be something like:

JS file:

function foo(link){
    window.location.href = link;
}

View file

<script>
    foo("@Url.Action('Index', 'Home')");
</script>

EDIT: This link provided by Maxwell Troy Milton King points to a similar question that has very good answers, give it a try if this solution isn't enough.

Community
  • 1
  • 1
rareyesdev
  • 2,337
  • 1
  • 25
  • 43
  • Ok, but is there any JS libaries to get simular opportunities or I must to right it myself? – Rustam Salakhutdinov Jul 12 '14 at 21:40
  • @RustamSalahutdinov I don't know how to archive that behavior on external files. What I do is declaring the function externally but calling inside the view file with arguments that are razor statements – rareyesdev Jul 12 '14 at 21:44