0

My ASP.NET MVC project works flawlessly when debugging locally.

However, once it is deployed to production, the true "Path" of the application is http://servername/virtualpath/Home/Index, just as an example.

There is some JavaScript that needs to declare the true baseUrl regardless of the environment it is deployed to.

In summary, I need a JavaScript variable to hold http://servername/virtualpath/ when it is deployed to such an environment, or just http://servername/ when it is running on an environment such as in debug.

blgrnboy
  • 4,877
  • 10
  • 43
  • 94

1 Answers1

0

To add on to the linked questions, if you're talking about static javascript files, you don't have access to your server code, so you've got a couple options:

You could put your javascript into an .aspx file or a regular controller action/view, so you do have access to your server code and can use things like Url.Content or ResolveUrl. If you do this, make sure you think about browser and/or server caching so that you don't waste resources.

myfile.js.aspx

<%@Page Language="C#" %>
<%
    Response.ContentType = "application/javascript";
    Response.Cache.SetCacheability(HttpCacheability.Public);
    Response.Cache.SetExpires(DateTime.Now.AddHours(1));
%>

var imagePath = "<%= ResolveUrl("~/images/myimage.png") %>";

Or on your layout page (before any other <script> tags), you could put a hidden field or piece of javascript with the relative path, then call it:

_Layout.cshtml:

<script>
    window.resolveUrl = function(url) {
        return "@Url.Content("~")" + url; // Handle slashes, nulls, etc...
    };
</script>

myfile.js

var imagePath = resolveUrl("images/myimage.png");
Joe Enos
  • 39,478
  • 11
  • 80
  • 136