jQuery Autocomplete with MVC Part 2
In Part 1 we created the MVC project and hooked it up to the Northwind database using the EntityFramework. We also brought in the jQuey Ui framework and created a simple autocomplete function that displayed a message showing the user who they selected. However we want to do more than just display a confirmation of who was selected. We want add two main features; navigate to the details of the selected customer, and on a form fill in the customer’s information.
In Part 2 we will see how these features can be implemented.
Navigating Based on Selection
We will be displaying the full details of the customer, so we need to create a page to display the information. In your home controller create a new AcionResult for CustomerDetail:
Create a strongly typed view for this action, be sure to select Details for the Scaffold template. Since we will not be using it, remove the ““Edit” link at the bottom of the CustomerDetail view.
Now that we know where we are going, we have to modify our javascript to send us ther. Back on the Index page change the “select” part of the javascript to:
That’s it, when you select one of the auto complete results you will navigate to the CustomerDetail display for that individual.
Form Completion
Now let’s see how to populate a form with results from the auto complete. Since we want more than just the contact and company name we will need to create a new JsonResult in our Home controller. The only part we need to change is the fields selected in the LINQ statement:
While still in the Home controller we will add a new ActionResult for the FillCustomerInfo view:
Create a new view from this action, and select the Edit Scaffold Template. The javascript for filling in the form is basically the same, so copy/paste the script and input text box. Change the ajax url to /home/FillForm (to get our additional fields). Modify the return results to accommodate the additional fields:
Now modify the “select” function to use some jQuery to find the form fields and stuff the data into the proper place:
That’s it. Run the project now and navigate to the FillCustomerInfo page. When you select a customer their details will populate the rest of the form.
Download Code: jQueryAutocomplete.zip
by TexasJetter