14

Possible Duplicate:
Url helper in java script

Url.Content(...) asp.net mvc helper method returns equivalent absolute URL. I'm searching for a method in jquery or javascript that works like this...

because, I want to separat javascript code into a file (.js) and you know that file doesn't supports Url.Content(...) inside javscript code....

url(...) method of jquery not works like Url.Content()

Updated: 22 Jan 2011

I have a workaround:

In the .cshtml file, I created a ‘GetPath’ function that returns absolute path including domain name and can be accessible inside any .js file.

Include following code in any ASP.NET MVC view (.cshtml or .aspx or .vbhtml):

<script type="text/javascript">
    var fullPath = '@HttpContext.Current.Request.Url.Scheme://@HttpContext.Current.Request.Url.Authority';
    function GetPath(url) {
        return fullPath + url;
    }
</script>
<script src="@Url.Content("~/JavaScriptFile.js")" type="text/javascript"></script>

And the code inside any javascript file.

$(function () {
    alert(GetPath('/Content/Site.css'));
});

The result is: http://www.yourDomain.com/Content/Site.css or localhost:1234/Content/Site.css >> Visual Cassini server

You just need to replace @Url.Content("") with GetPath('') in any .js file.

http://muaz-khan.blogspot.com/2012/02/absolute-or-relative-url-issues-and.html

peterh
  • 11,875
  • 18
  • 85
  • 108
Muaz Khan
  • 7,138
  • 9
  • 41
  • 77

2 Answers2

1

Have a look at ASP.NET MVC JavaScript Routing

Giorgi
  • 30,270
  • 13
  • 89
  • 125
0

Also,

there's a great example here:

do you write your JavaScript in a ASP.NET MVC view ... or in a separate JavaScript file?

that uses the data attributes on jquery to store arbitary objects for exactly the purpose that you propose. Check out the accepted answer for the full details.

Community
  • 1
  • 1
jim tollan
  • 22,305
  • 4
  • 49
  • 63