Raja
Raja

Reputation: 391

Relative Image URL in Javascript File - ASP.net MVC and IIS 7

I am developing an Asp.net mvc application, everything works fine in ASP.net development server but when I am trying to host it on IIS 7. I am getting problem related to URL resolution. I have used relative paths in Javascript to give the image. The script file is in ~/Scripts/ folder and image files are in ~/Content/images/ folder. Now in the javascript file I am trying to use the give by giving the relative path like http://localhost/WebApp1/controller1/action1/ it tries to find it at http://localhost/controller1/action1/ and couldn;t find the file.

Upvotes: 4

Views: 15058

Answers (4)

willie55
willie55

Reputation: 1

I have had this issue in the past, try using tilde

~/controller1/action1/

Upvotes: 0

Leng
Leng

Reputation: 11

I had and same problem and found an element solution by David Banister. The issue is with MVC controller's index action that returns a URL in the form of (www.mysite.com/viewName, as opposed to www.mysite.com/viewName/index) that the web browser later would fail when trying to reference css or js files using relative path syntax (../../).

His solution works well for me. Hope this helps someone. Good luck.

http://blog.davidbanister.com/2010/09/28/mvc-fixes-relative-path-issues-in-asp-net-mvc-2/

Upvotes: 1

BenAlabaster
BenAlabaster

Reputation: 39806

If how I'm reading this is correct, you're now running the WebApp from the domain root of IIS7 now instead of WebApp1 from your development environment?

So, if my assumption is correct, then ~/ should now resolve to http://localhost/ instead of http://localhost/WebApp1/

If that is all still correct, then your folder structure has all moved up one level with your ~/scripts folder in the absolute path:

http://localhost/Scripts/

and your images folder as:

http://localhost/Content/Images/

In order to access your images from your scripts, you can use a number of methods. The simplest is to use the relative path from your scripts directory: "../Content/Images/MyImage.jpg"

Or you can use document.location.host to build the fully qualified path name within the javascript: document.location.host + "/Content/Images/MyImage.jpg"

Another method is to have ASP.NET build this part of the script dynamically so that the fully qualified path name is injected.You can do this by using ScriptManager.RegisterStartupScript or ScriptManager.RegisterScriptBlock

There's really many ways to skin this cat, they're just the first 3 I can think of off the top of my head.

Upvotes: 4

IrishChieftain
IrishChieftain

Reputation: 15253

Try:

<a href="~/controller1/action1/" id="testLnk" runat="server">

The runat attribute should ensure that the framework resolves it. You can also use the ResolveUrl method.

Upvotes: 1

Related Questions