Rustam Salakhutdinov
Rustam Salakhutdinov

Reputation: 804

Url.Action in JS don't work

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?

Upvotes: 3

Views: 3653

Answers (1)

rareyesdev
rareyesdev

Reputation: 2427

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.

Upvotes: 3

Related Questions