ASP.NET MVC Razor – Separate JavaScript code while taking advantage of full link – as Url.Content() does


Note: Current blog-post is old. You can find latest/new blog post here:

Javascript absolute URL issues

If you are using a free hosting service like aspspider.com, then there is a lot of bad stuff will happen for you when you host your website!

The biggest problem I found when I hosted my website in a free hosting service was absolute URL problem.

In ASP.NET MVC view engine, we can use Url.Content(..) helper method for absolute URL but we cannot use it inside a javascript file.

I came up a solution for using same technique inside separate javascript file.

<script type="text/javascript">
      var domainName = '@HttpContext.Current.Request.Url.Scheme://@HttpContext.Current.Request.Url.Authority';
</script>

Just insert this code snippet inside ~/Views/_ViewStart.cshtml file and use it like this in separate javascript file.

[Note: _ViewStart.cshtml executes before any other views and merged with other views so you don’t have to place above code inside every view.]

Javascript.js [Separate javascript file]:

$.ajax( {
            url: domainName + '/Controller/Action',
            type: 'POST',
            success: {}
});
Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s