Reputation: 3869
My image path references (src='/images/image.jpg') inside my .js files are failing when there is a virtual directory as the virtual directory gets included to the path hierarchy
I can deal with this on other areas of my application where I have server methods to give me the correct path info.
What is a good way to deal with this for .js files?
Upvotes: 1
Views: 2631
Reputation: 42497
I created a handler such as this to output some environmental parameters for reuse in various JS objects:
/Environment.ashx/.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MvcApplication2
{
/// <summary>
/// Summary description for $codebehindclassname$
/// </summary>
public class Environment : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/javascript";
context.Response.Cache.SetCacheability(HttpCacheability.Public);
context.Response.Cache.SetExpires(DateTime.Now.AddSeconds(600));
context.Response.Write(String.Format("Environment = {{ RootPath:\"{0}\" }};", context.Request.ApplicationPath)); // set any application info you need here
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
Enable the handler in your web.config:
<configuration>
<system.web>
<httpHandlers>
<!-- ... -->
<add verb="*" path="environment.ashx" validate="false" type="MvcApplication2.Environment, MvcApplication2"/>
</httpHandlers>
</system.web>
Set up your master or content ASPX page (below assumes ASP.NET MVC):
<html>
<head>
<!-- set up your other JS includes, etc. ... -->
<script src="<%=Url.Content("~/environment.ashx"); %>" type="text/javascript"></script>
</configuration>
</head>
</html>
Now, for all JS objects and scripts that assume Environment.ashx was already loaded, you can reference Environment.RootPath
var imagePath = Environment.RootPath + "images/image.jpg";
Upvotes: 0
Reputation: 846
Can you pass in a path parameter to your function ?
// in the code behind
String imagePath = Page.ResolveClientUrl("~/images/");
...
<%-- in mark up --%>
doSomething('<%= imagePath %>');
...
// in js
function doSomething(path) {
var imageSrc = path + '/image.jpg';
}
There will be ways of making it more elegant but that's the general idea.
Upvotes: 3
Reputation: 101
I'm assuming you're running a flavor of Unix. You have a couple of options that I'm sure will work, and one that I'm not sure of:
Upvotes: 0
Reputation: 7484
The references will be from the location of the js files; not from the application root. Assuming you have a js directory off your root, try adding a .. in the path to the image (../images/image.jpg).
Upvotes: 3