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>
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.
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.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With