How do you get an ASP.NET application relative开发者_JS百科 URL from JavaScript?
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>
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:
- 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.
- 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.
In order to get the application's relative URL, you can use
Request.ApplicationPath
which requires a request context.
To transform a complete path, use
System.Web.VirtualPathUtility.ToAbsolute(path)
which can be used without context.
If you are on an .aspx page, you can use the ResolveUrl
method of the page.
For more information see Different approaches for resolving URLs in ASP.NET as pointed to by @pranay-rana in Getting full URL from URL with tilde(~) sign.
精彩评论