views:

252

answers:

2

When we have a .js file which we reference from a View page and then have URLs in callback in JS file we run into problems with urls not being resolved when running site either on VS 2008 integrated webserver or on IIS7.

For example, we have this piece of code in JS file

pending.createCallback(pending.webRoot + "../../WidgetZoneV2/MoveWidget/" + sData, pending.widgetAdmin.moveComplete);

This piece of code works fine when run with integrated webserver (on the URL http://localhost:54354/WidgetZoneV2/) but fails on IIS7 where we have an URL like this http://localhost/virtualdir/WidgetZoneV2, because it the later case the URL in the callback gets translated into http://localhost/WidgetZoneV2 which of course does not exist.

How do you handle this sort of cases? As far as I can see the only option is to dinamically create JS at runtime.

+1  A: 

i have a vb.net function i use for precisely this sort of situation. to follow convention i use the ASP.NET relative site root character '~' and resolve any instances of this char followed by a '/' to the full virtual root as follows

    Public Shared Function ResolveUrl(ByVal URL As String) As String
        If URL.StartsWith("~") Then
            Return (HttpContext.Current.Request.ApplicationPath & URL.Substring(1)).Replace("//", "/")
        Else
            Return URL
        End If
    End Function

so your code would be

pending.createCallback(pending.webRoot + ResolveUrl("~/WidgetZoneV2/MoveWidget/") + sData, pending.widgetAdmin.moveComplete);

I actually implement this a string extension method but i dont have that code on the machine im writing this from

hope this helps

dave lowe
This looks fine but would .NET code run from within .JS file? Coz I don't insert my JavaScript directly into the view but rather link to it.
mare
oh sorry my mistake. well what you could do is send the js files through a handler and the you can alter with code. i did a post on my blog explaining this http://www.thecodeface.co.uk/Post/View/1
dave lowe
+1  A: 

If your js files in "/Scripts" folder, and file name is widget.js. Path get client script used jQuery.

var widgetSrc = $("script[src*=/widget.js]:first").attr("src");
var path = widgetSrc.substring(0, widgetSrc.indexOf("/widget.js"));
takepara