views:

67

answers:

2

How do you get an ASP.NET application relative URL from JavaScript?

+1  A: 

Client-side code (JavaScript) has no concept of server-side component boundaries (like an asp.net app) so there's no nice and easy 'native' way for JavaScript to do that (that I know of).

The best (probably awful) method I've used to get around that is to have the asp.net app provide that info to the script when the page is served; there's a couple of options:

  1. Include a hidden-field/TextBox/whatever and set the value of it to any server generated value you want; obviously JavaScript will be able to read the value easily enough.
  2. Have asp.net/your app dynamically write/generate part of the JavaScript, when it does it writes the value as a variable where your other JavaScript can reference it.
Adrian K
+2  A: 

You could always generate a set of constants for paths that you will be using in a way which Javascript can see. ex:

<script type="text/javascript">
    var Paths = {};
    var Paths.Images = '<%= ...MapPath("~/images") %>';
    var Paths.Scripts = '<%= ...MapPath("~/scripts") %>';
</script>

Of course, you can adapt this to your app's needs. For example, it might not be a bad idea to stick the initial declaration of Paths in a common js file, and have a method in your master page to add paths you will definitely need on each page. Subpages can generate paths as needed, possibly from a helper method of some sort that generalizes the whole process.

edit: I've been thinking about this some more. Here's a possible implementation, completely untested and probably not exactly right:

public static string RegisterPathsForJavascript(IDictionary<string,string> paths)
{
    var pathConstants = "";
    foreach(var path in paths)
    {
        pathConstants += string.Format("Paths.{0} = '{1}';\n",
            path.Key,
            Server.MapPath(path.Value));
    }
    return pathConstants;
}

and in your page:

<script type="text/javascript">
    <%= RegisterPathsForJavascript(new Dictionary<string, string> {
            { "Images", "~/images" },
            { "Scripts", "~/scripts" }
        }) %>

    alert(Paths.Images);
</script>
Stuart Branham