Sometimes we need to send a request to the server via an asynchronous call, the advantage of this is that we are not doing a full page refesh and wasting bandwidth for something that could be as simple as returning a thank you message.
There are many ways of doing this such as using XHR(XMLHttpRequest) but for this example I will be using jQuery and Ajax, which will send a request to a MVC controller and return the results.
AjaxFindDetails is the ID of our div which will display the results of the async call to the MVC controller, if any results are found, they will be displayed here. If no results a found, then a message informing the user no results are found will display.
The code for the controller can be seen below:
The view contains a simple form with a textbox, once you enter either 'dog', 'cat' or 'fish' it will do an asynchronous call using jQuery and Ajax to the controller and do a search for the keyword. If a match is found, the results are displayed in the div else a message is shown that no results are found.
The rest of the code for this example can be found below.
The test data is a simple list that just returns a list of dogs, cats and fish.
The view model is a simple class that just has properties for the test data to hold the dog data.
The view contains a simple form with one textbox, enter 'dog','cat' or 'fish' and this will fire the asynchronous call to the jQuery code that has a on change function that waits for the textbox value to change.