Creating a cross site request using jQuery, Ajax and C# MVC

I recently had to create an add-in that allowed dynamic searching. Sometimes this is known as typeahead. This was to be used on our core workflow application which was developed in ClassicASP and is still running happily. Given the size of the data set and the performance required I developed the add-in using C#/MVC that returns a JSONP data set to the calling application for it to render as a dynamic list, any item of which can then be clicked on to use as a shortcut.

There were a couple of challenges with this approach

  • How to deal with CORS
  • How to get AJAX to get the data

In order to deal with the CORS problem, I decided to use JSONP, which is JSON with Padding. To get my controller to return a correctly formatted list it was necessary to create a custom action result class derived from the inbuilt JsonResult class – taken from this fine blog:

https://www.codeguru.com/csharp/.net/net_asp/using-jsonp-in-asp.net-mvc.htm

My controller can then use Linq to SQL to create the data list and return it via:

JsonpResult result = new JsonpResult(amodel);
return result;

The next part is to create the AJAX element so that it does not fall foul of CORS. There is a lot of information regarding this bit on the Internet but not always brought together is a way that makes sense. The key part is to include “callback=?” on the url. I also needed to pass other data items – in my case passed through html5 data tags as there was a version for our live system and test system. My jQuery ended up looking like this:

    $(document.body).on(‘keyup’, ‘#search’, function () {
        var search = $(‘#search’).val();
        var datafield = $(this);
        var associate=datafield.data(‘associate’);
        var domain = datafield.data(‘domain’);
        var analytics = datafield.data(‘analytics’);
        var url = analytics + ‘/Search/GetCases?callback=?’;
        // Only hit the server if the search string is greater than or equal to 3 characters.
        if(search.length >= 3){
            $(“#update”).hide();
    $.getJSON(url, { q: search, associate: associate, domain: domain }, function (data) {
    var output = ‘<ul>’;
    $.each(data,function(key, val){
                    if (val.Url == “#”){
                        output += val.CaseData;
                    }
                    else {
                        output += ‘<a href=”‘ + val.Url + ‘”>’ + val.CaseData + ‘</a>’;
                }
});
            output+='</ul>’;
            $(‘#update’).html(output);
            $(“#update”).show();
     })
    }
})
You can see that I have appended ?callback=? to the url being passed to the getJSON call as well as passing in additional data items. I could have used a standard AJAX call with type: GET, in which case I could have used:

 

dataType: ‘jsonp’,

jsonp: ‘callback’

The callback function can be named explicitly and used in the function(data) part.

With all those bits wired up to my search box and a bit of CSS to style the returned data I ended up with an incredibly performant seach function.

I plan to continue to extend my C#/MVC server app to  offer a number of other centralised features – AJAX file uploads, document encryption and decryption and image manipulation – all of which our very difficult to do in ClassicASP.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

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

Google photo

You are commenting using your Google 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 )

Connecting to %s