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

  • AI for GitHub Collaboration? Maybe Not So Much

    No doubt GitHub Copilot has been a boon for developers, but AI might not be the best tool for collaboration, according to developers weighing in on a recent social media post from the GitHub team.

  • Visual Studio 2022 Getting VS Code 'Command Palette' Equivalent

    As any Visual Studio Code user knows, the editor's command palette is a powerful tool for getting things done quickly, without having to navigate through menus and dialogs. Now, we learn how an equivalent is coming for Microsoft's flagship Visual Studio IDE, invoked by the same familiar Ctrl+Shift+P keyboard shortcut.

  • .NET 9 Preview 3: 'I've Been Waiting 9 Years for This API!'

    Microsoft's third preview of .NET 9 sees a lot of minor tweaks and fixes with no earth-shaking new functionality, but little things can be important to individual developers.

  • Data Anomaly Detection Using a Neural Autoencoder with C#

    Dr. James McCaffrey of Microsoft Research tackles the process of examining a set of source data to find data items that are different in some way from the majority of the source items.

  • What's New for Python, Java in Visual Studio Code

    Microsoft announced March 2024 updates to its Python and Java extensions for Visual Studio Code, the open source-based, cross-platform code editor that has repeatedly been named the No. 1 tool in major development surveys.

Subscribe on YouTube