Practical .NET

Generate Reliable URLs in ASP.NET MVC AJAX Calls

You've moved your ASP.NET MVC application into production and all of your lovely AJAX calls have started failing. The solution is to ensure the URLs you're using in your AJAX calls are absolutely correct.

In so much of the AJAX-related sample code you see, you'll find wonderful, terse URLs, like this:

$.getJSON('FI/GetItem', function(data) {…

Or like this:

$.ajax({
  data: criteria,
  datatype: "application/json",
  type: "POST",
  url: "MI/DeleteItem/" + ItemID,
  cache: false,
  success: function (result) {...

You've seen these URLs in sample code that I've provided in my columns, for example. But the truth is that, once you move out of testing in Visual Studio, these relative URLs aren't reliable. What worked in test won't work when you move your application to production. You'll find you're a victim of how the page was retrieved (did the user select a bookmark, click a submit button?), of the browser your code is executing in, and whether you're running the browser on the server or on a remote computer. While these terse URLs have the advantage of being easy to explain in articles (like this one), they aren't guaranteed to work in your production applications.

In fact, there's only one 100 percent reliable way to write URLs that will never fail: Use absolute URLs that begin with "http://" and map out the whole path to the action method in the controller you want to execute. Of course, you'd be an idiot to write those URLs out yourself because your site or server name might change (in fact, your site and server names are guaranteed to change as you move from development to test to production). Even if the site or server name doesn't change, what happens if you build your URLs with HTTP as the scheme and your site is accessed with HTTPS?

Dynamically Generating Absolute URLs
Fortunately, ASP.NET MVC gives you a variety of ways to generate an absolute URL without having to hardcode in your server and site names. Personally, I like the Action method on the UrlHelper object (in a View, you can retrieve the UrlHelper object from the View's Url property), which has the benefit of generating your URL when your View is requested, based on the format of the URL used to request your View.

The URL object's Action method must be passed four things:

  • The name of the action method you want to call.
  • The name of the controller class in which the method is (minus the "Controller" at the end of the name).
  • An anonymous class containing any additional parameters.
  • The scheme (HTTP, HTTPS) used in the URL that requested your view. (You can retrieve that through the Request object.)

I've got to be honest: This is a solution that involves a lot of typing. Here's an example that uses the Action method in a getJSON call, providing just the action method and controller names:

  $.getJSON('@Url.Action(
    "GetItem", "FindItem", new  { }, Request.Url.Scheme)', function(data) {...

You can see, following the controller name ("Search"), that I've provided a dummy anonymous object that can be used to add parameters to the AJAX request, though I didn't take advantage of that feature in this example.

Here's an example of a full $.ajax call, this time using the anonymous object to add a parameter to the request called "itemid." In this example, the actual value of the parameter is held in a variable called ItemID:

$.ajax({
  data: criteria,
  datatype: "application/json",
  type: "POST",
  url: '@Url.Action(
    "DeleteItem", "ManageItem", new  {itemid = '@ItemID' }, Request.Url.Scheme)',
  cache: false,
  success: function (result) {...

As I said, this is a solution that commits you to a lot of typing. However, I like that the action and controller names are obvious and easy to change and that adding and removing parameters to the call is relatively straightforward.

And there's another advantage: It always works.

About the Author

Peter Vogel is a system architect and principal in PH&V Information Services. PH&V provides full-stack consulting from UX design through object modeling to database design. Peter tweets about his VSM columns with the hashtag #vogelarticles. His blog posts on user experience design can be found at http://blog.learningtree.com/tag/ui/.

comments powered by Disqus

Featured

  • VS Code Copilot Previews New GPT-4o AI Code Completion Model

    The 4o upgrade includes additional training on more than 275,000 high-quality public repositories in over 30 popular programming languages, said Microsoft-owned GitHub, which created the original "AI pair programmer" years ago.

  • Microsoft's Rust Embrace Continues with Azure SDK Beta

    "Rust's strong type system and ownership model help prevent common programming errors such as null pointer dereferencing and buffer overflows, leading to more secure and stable code."

  • Xcode IDE from Microsoft Archrival Apple Gets Copilot AI

    Just after expanding the reach of its Copilot AI coding assistant to the open-source Eclipse IDE, Microsoft showcased how it's going even further, providing details about a preview version for the Xcode IDE from archrival Apple.

  • Introduction to .NET Aspire

    Two Microsoft experts will present on the cloud-native application stack designed to simplify the development of distributed systems in .NET at the Visual Studio Live! developer conference coming to Las Vegas next month.

  • Microsoft Previews Copilot AI for Open-Source Eclipse IDE

    Catering to Java jockeys, Microsoft is yet again expanding the sprawling reach of its Copilot-branded AI assistants, previewing a coding tool for the open-source Eclipse IDE.

Subscribe on YouTube

Upcoming Training Events