Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 747
Rustam Salakhutdinov Avatar asked Dec 05 '25 04:12

Rustam Salakhutdinov


1 Answers

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.

like image 100
rareyesdev Avatar answered Dec 07 '25 20:12

rareyesdev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!