Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

URL helper in JavaScript

I'm using jQuery Lightbox for my image gallery.
The URL for the button image is '../../Content/Lightbox/lightbox-btn-next.gif'
That works fine if my URL is 'localhost/Something1/Somtehing2'
If I use another route like 'localhost/Something1/Something2/Something3' then URL to button images is incorrect.
Can I use Url.Action() inside .js files?
This is how I call .js files:

<script type="text/javascript" src="<%= Url.Content("~/Scripts/jquery.lightbox-0.5.js") %>"></script>
like image 963
šljaker Avatar asked Feb 10 '10 10:02

šljaker


People also ask

What is URL in JavaScript?

url. A string or any other object with a stringifier — including, for example, an <a> or <area> element — that represents an absolute or relative URL. If url is a relative URL, base is required, and will be used as the base URL. If url is an absolute URL, a given base will be ignored. base Optional.

What is a URL object?

The vanilla JavaScript URL object is used to parse, construct, normalize, and encode URLs. It provides static methods and properties to easily read and modify different components of the URL.


2 Answers

I put the following in my master page, which accomplishes much the same thing as @Url.Content('~/path'):

<script type="text/javascript" charset="utf-8">
    function UrlContent(path) {
        return '@Url.Content("~/")' + path.replace(/^\//, ''); 
    }
</script>

When my master page is compiled and served up this translates into a javascript function that applies my site root to the path. Works great. The path.replace regex simply removes a leading slash if there is one since @Url.Content("~/") has a terminating slash.

like image 118
Matt Penner Avatar answered Nov 14 '22 03:11

Matt Penner


You can't use Url.Action() inside .js files. But you can define global variable and use it in you js file.

<script type="text/javascript">

    var imageUrl = "<%= ... %>";

</script>
like image 20
Serhiy Avatar answered Nov 14 '22 01:11

Serhiy