views:

251

answers:

2

I'm using jquery lightbox for image gallery.
Url to the button image is '../../Content/Lightbox/lightbox-btn-next.gif'
That work 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>
A: 

I prefer to pull the URLs from a tags 'href's or form 'action's - or some other element that makes sense.

<img class="_click" src="<%= Url.Content("~/my/image.png") %>" alt="Click" />

And in my javascript (double check this on jQuery, I am not sure if it's the exact syntax.):

var url = $('._click').attr('href');
// To pass these to your plugin as options
// see lightbox source for a full list
$('a').lightBox({ imageLoading : url })

Another slightly less preferred option is to add your settings on top of your file:

<script type="text/javascript"><![CDATA[
    $('a').lightBox({ imageLoading : <%= Url.Content("~/my/image.png") %> })
//]]></script>

I said 'less preferred' because this approach mixes markup and code.

Yet another approach (which needs a lot of tidy up) is to serve you js file from a controller:

public ActionResult GetFileContent(string filename)
{
    // important: make sure to control the path for security
    var path = Server.MapPath("~/Scripts/" + filename);
    var content = System.IO.File.ReadAllText(path);

    // Use some kind of template convention
    content = content.Replace("{{IMAGE_PATH}}", Url.Content(@"~/my/image.png"));

    var bytes = new UTF8Encoding().GetBytes(content);
    return new FileContentResult(bytes, "text/javascript");
}
Maxwell Troy Milton King
The url is inside jquery.lightbox-0.5.jsI don't have an a tag inside View.
šljaker
Maybe you can use the script tag? Where are you running your lightbox() call?
Maxwell Troy Milton King
I'm running lightbox call inside partial view. There is an explanation on http://leandrovieira.com/projects/jquery/lightbox how these settings can be overridden. But that doesn't work :)
šljaker
Maybe I explained a bit complicated :) In jquery.lightbox-0.5.js there is a setting called imageBtnClose. It's a string representing url of button images (not the images inside an a tag). When I change the route, I have to change that setting in jquery.lightbox-0.5.js and cannot reuse the same .js file on different views.
šljaker
That's why I want to use Url.Action inside .js file so I can reuse it on other views and I do not have to re-configure it when I change the route.
šljaker
just added yet another approach, see if that helps :)
Maxwell Troy Milton King
A: 

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>
Сергій
Tnx! That solved my problem.
šljaker