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:
My controller can then use Linq to SQL to create the data list and return it via:
JsonpResult result = new JsonpResult(amodel);
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:
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.