2

I have ASP.NET MVC actions that return JSON data. My client uses jQuery's ajax function to retrieve this data and display it on the screen. I use absolute paths to the controller actions in my JavaScript:

$.ajax({
    url: '/Home/Load',
    type: 'post',
    dataType: 'json'
})

The problem is that in some environments, we'll add an extra virtual directory to the front, so the URL is actually /Path/To/App/Home/Load. I am wondering whether there is a way to write my JavaScript so that it doesn't need updated each time I deploy. I could use relative URLs, like ../Home/Index, but occasionally I move my JavaScript code around. Things get extra tricky when using MVC's bundler, too. It would be nice if the ~ character worked.

Travis Parks
  • 8,435
  • 12
  • 52
  • 85

2 Answers2

4

Here is how I do:

Add the following lines in your main view (here with the Razor syntax):

<script type="text/javascript">
    var appBaseUrl = "@Url.Content("~")";
</script>

Then in Javascript:

$.ajax({
    url: appBaseUrl + 'Home/Load',
    type: 'post',
    dataType: 'json'
})
Olivier Payen
  • 15,198
  • 7
  • 41
  • 70
  • I like this approach. The only downside is that it results in a warning because it inter-mixes razor and JavaScript. I combined both your and @Richard Dalton's approach. `` – Travis Parks Feb 28 '13 at 15:54
2

You could put the URL into an element that is relevant to your ajax request:

<div id="mydiv" data-url="@Url.Action("Load", "Home")">Click me to load ajax request!</div>

Then change your JS code to:

$.ajax({
    url: $('mydiv').data('url'), // Could be $(this).data('url') if clicking to load
    type: 'post',
    dataType: 'json'
})

The advantage of this is that it still uses MVCs routing so any custom routes will still work.

Richard Dalton
  • 35,513
  • 6
  • 73
  • 91