URL helper in JavaScript

2019-02-05 02:01发布

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>

4条回答
倾城 Initia
2楼-- · 2019-02-05 02:28

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");
}
查看更多
倾城 Initia
3楼-- · 2019-02-05 02:29

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>
查看更多
甜甜的少女心
4楼-- · 2019-02-05 02:44

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.

查看更多
倾城 Initia
5楼-- · 2019-02-05 02:47

Just put @Url.Content(@"~/some paths") into single quotes such as this:

'@Url.Content(@"~/some paths")'
查看更多
登录 后发表回答