Microsoft and jQuery Ajax calls – not using standards

I recently started using C# and .NET for the first time to build a web application. It is just a proof of concept application where I am trying to implement CRUD (Create, Read, Update and Delete) though jQuery and Ajax calls from a simple webpage. The application should let me retrieve a list of all companies in the database, get information about a specific company (based on a company id), update an existing company (and create a new company in the database if it does not exist) and finally allow a company to be deleted.

I been doing these things for years using IBM Domino as the backend, simple reading the query string and parsing the name-value pairs before performing actions based on the values. So when I started using Visual Studio I naturally thought things would work the same there.

But I found out that ASP.NET is using a different method to address web resources. It uses the concept of routes, so instead of adding information passed to the server using the query string, the data is passed in the actual URL:
To get a list of all companies you would call /api/Company, and to get information about a specific company you add the company id (/api/Company/Q1234). If I want to pass two arguments to the server, for example to get all companies in a specific city and state, you would call /api/Company/TX/Dallas.

In my opinion, this gives you much less flexibility than if  you pass arguments in the query string. You must put the arguments in the correct order, and it is much harder to use optional arguments. One example of where I used optional argumenst is for sort order. In some cases I want the companies to be returned in descending order, instead of the default ascending. Or I want to sort on a specific column/values. In those cases I pass along a special argument, but normally I don’t. Less data to transfer that way, and cleaner code. But it still works.

It is when you want to perform a POST of form data to the server that it get really complicated and annoying. This is the sample code using the ASP.NET Web API generated by Visual Studio 2013:

// POST: api/Company
public void Post([FromBody]string value)
{
    ... do stuff here
}

As you perhaps can tell, this function only take one argument, which is pretty useless in a real application. And you can’t just add additional arguments in the declaration. One way to do it (as described here) is to use a data transfer object containing all the arguments, which then is used in the function:

public class CompanyDTO
{
    public string CompanyID { get; set; }
    public string LegalName { get; set; }
    public string Address { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public string ZIP { get; set; }
}

// POST: api/Company
public string Post(CompanyDTO Company)
{
    return Company.LegalName + " in " + Company.City + ", " + Company.State;
}

The issue here is that you need to put the arguments in exactly the same order in the Ajax call (and hence the query string) as they are declared in the code. You also can’t (as far as I understand) send only updated values, you need to always send all the fields, even if just one field has been changed.

So what should one do? The best solution I found this far is to pass the data from the browser as a string, containing JSON. Not as a JSON object, as that will not work.

So do not do this:

$.ajax({
    type: "POST",
    url:  "api/Company/",
    data: {'city':'Dallas','legalname':'Test Company, LLC'},
    contentType: "application/json; charset=utf-8",
    dataType: "json"
});

The browser will just convert the JSON object to name-value pairs, and you end up with null in your code. Instead, change the jQuery code to this:

$.ajax({
    type: "POST",
    url:  "api/Company/",
    data: "{'city':'Dallas','legalname':'Test Company, LLC','Owner':'Karl-Henry Martinsson'}",
    contentType: "application/json; charset=utf-8",
    dataType: "json"
});

Now it will work! Notice the small change, I added quotes around the JSON. An added bonus is that you don’t need to pass along all fields, just the ones you want/need in any order. And if you pass along a field/name that is not defined on the server, it will simply be ignored.

You probably don’t want to build the data string manually. Perhaps you want to loop though certain fields and retrieve the values to pass to the server. You would do something like this:

// Create a new empty object
var Company = { };
// Loop through all elements with the class 'dataField' and
// build an object with the ID of the element as the name.
$('.dataField').each(function() {
  Company[this.id] = this.value;
});

$.ajax({
  type: "POST",
  contentType: "application/json; charset=utf-8",
  url: "/api/Company",
  data: JSON.stringify(Company),
  dataType: "json"
});

I use JSON.stringify to convert the JSON object to a string before sending it to the server.

So this is what I found out. Hopefully it will help someone. I am still a bit frustrated that Micorosft once again decided to do things a different way than the rest of the world, but I guess one should not be surprised at that.

 

 

 

 

This Post Has 3 Comments

  1. Brian Moore

    Wait until you try to address more than one table at a time. Like writing to a second table as a transaction log.

  2. Stephan H. Wissel

    Actually using routes is how everybody but Domino does it 🙂 REST APIs revolve around routes. The general idea is: the route says what you want to interact with, while parameters specify how (e.g. ?output=verbose)

  3. Krister Renaud

    REST conventions were defined by W3C so I would say that it is a standard. A standard that works very well for some use cases, less well for others.

    There are also some other methods to consider when using REST. Such as using other paths like /objectBySOMECONDITION/MYSEARCHCRITERIA_1/MYSEARCHCRITERIA2 (/companiesByCity/TX/Dallas) or using the HTTP Range header.

Leave a Reply