MultiSelect Autocomplete Textbox In MVC 5

Introduction

In this article, I will demonstrate how to create a multi-select jQuery autocomplete textbox using MVC 5. I will use jQuery autocomplete plugin and Bootstrap 4.

Step 1

Open SQL server 2014 and create a database table.

  1. CREATE TABLE [dbo].[Skill](  
  2.     [Id] [int] IDENTITY(1,1) NOT NULL,  
  3.     [Language] [nvarchar](50) NULL,  
  4.  CONSTRAINT [PK_Skill] PRIMARY KEY CLUSTERED   
  5. (  
  6.     [Id] ASC  
  7. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  8. ON [PRIMARY]  
  9.   
  10. GO  

Step 2

Open Visual Studio 2015, click on New Project and create an empty web application project.

Screenshot for creating new project 1

ASP.NET

 

After clicking on New Project, one window will appear. Select Web from the left panel, choose ASP.NET Web Application, give a meaningful name to your project, and then click on OK as shown in below screenshot.

Screenshot for creating new project 2

ASP.NET

 

After clicking on OK one more window will appear; choose empty, check on MVC checkbox and click on OK as shown below screenshot.

Screenshot for creating new project 3

ASP.NET

 

After clicking OK, the project will be created with the name of MvcMultiSelectAutocomplete_Demo.

Step 3

Add Entity Framework now. For that, right click on Models folder, select Add, then select New Item, then click on it.

Screenshot for adding entity framework 1

ASP.NET

 

After clicking on a New item, you will get a window; from there, select Data from the left panel and choose ADO.NET Entity Data Model, give it the name DBModels (this name is not mandatory you can give any name) and click on Add.

Screenshot for adding entity framework 2

ASP.NET

 

After you click on "Add a window", the wizard will open, choose EF Designer from the database and click Next. 

Screenshot for adding entity framework 3

ASP.NET

After clicking on Next a window will appear. Choose New Connection. Another window will appear, add your server name if it is local then enter a dot (.). Choose your database and click on OK.

Screenshot for adding entity framework 4

ASP.NET

The connection will be added. If you wish to save connect as you want. You can change the name of your connection below. It will save connection in web config then click on Next. 

Screenshot for adding entity framework 5

ASP.NET

After clicking on NEXT another window will appear to choose database table name as shown in the below screenshot then click on Finish.

Screenshot for adding entity framework 6

ASP.NET

Screenshot for adding entity framework 7

ASP.NET

Entity framework will be added and respective class gets generated under the Models folder.

Screenshot for adding entity framework 8 

ASP.NET

Following class will be added, 

  1. namespace MvcMultiSelectAutocomplete_Demo.Models  
  2. {  
  3.     using System;  
  4.     using System.Collections.Generic;  
  5.       
  6.     public partial class Skill  
  7.     {  
  8.         public int Id { get; set; }  
  9.         public string Language { get; set; }  
  10.     }  
  11. }  

Step 4

Right click on Controllers folder, select Add, then choose Controller as shown in below screenshot,

ASP.NET

After clicking on the controller a window will appear to choose MVC5 Controller-Empty click on Add.

ASP.NET

After clicking on Add another window will appear with DefaultController. Change the name to HomeController then click on Add. HomeController will be added under Controllers folder. Remember don’t change the Controller suffix for all controllers, change only highlight, and instead of Default just change Home as shown in the below screenshot.

ASP.NET

Complete code for controller 

  1. using MvcMultiSelectAutocomplete_Demo.Models;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Web;  
  6. using System.Web.Mvc;  
  7.   
  8. namespace MvcMultiSelectAutocomplete_Demo.Controllers  
  9. {  
  10.     public class HomeController : Controller  
  11.     {  
  12.         // GET: Home  
  13.         public ActionResult Index()  
  14.         {  
  15.             return View();  
  16.         }  
  17.         [HttpGet]  
  18.         public ActionResult Search(string term)  
  19.         {  
  20.             using (DBModel db=new DBModel())  
  21.             {  
  22.                 return Json(db.Skills.Where(p => p.Language.Contains(term)).Select(p => p.Language).ToList(), JsonRequestBehavior.AllowGet);  
  23.             }  
  24.         }  
  25.     }  
  26. }  

Step 5

Right-click on index action method in the controller. Add view window will appear with default index name unchecked (use a Layout page) and click on Add as shown in the below screenshot. The view will be added in the views folder under Home folder with name index.

Screenshot for adding view

ASP.NET

Step 6

Add required script and style in head section of view. 

  1. <link href="~/Content/bootstrap.min.css" rel="stylesheet" />  
  2. <script src="~/scripts/bootstrap.min.js"></script>  
  3. <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">  
  4. <link rel="stylesheet" href="/resources/demos/style.css">  
  5. <script src="https://code.jquery.com/jquery-1.12.4.js"></script>  
  6. <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>  

Step 7

Write script to retrieve data from database.

  1. <script type="text/javascript">  
  2.         $(function () {  
  3.   
  4.             function split(val) {  
  5.                 return val.split(/,\s*/);  
  6.             }  
  7.             function extractLast(term) {  
  8.                 return split(term).pop();  
  9.             }  
  10.   
  11.             $("#myAutocomplete")  
  12.           // don't navigate away from the field on tab when selecting an item  
  13.           .on("keydown"function (event) {  
  14.               if (event.keyCode === $.ui.keyCode.TAB &&  
  15.                   $(this).autocomplete("instance").menu.active) {  
  16.                   event.preventDefault();  
  17.               }  
  18.           })  
  19.             .autocomplete({  
  20.                 minLength: 0,  
  21.                 source: function (request, response) {  
  22.                     $.getJSON('@Url.Action("Search","Home")', {  
  23.                         term: extractLast(request.term)  
  24.                     }, response);  
  25.                 },  
  26.                 focus: function () {  
  27.                     // prevent value inserted on focus  
  28.                     return false;  
  29.                 },  
  30.                 select: function (event, ui) {  
  31.                     var terms = split(this.value);  
  32.                     // remove the current input  
  33.                     terms.pop();  
  34.                     // add the selected item  
  35.                     terms.push(ui.item.value);  
  36.                     // add placeholder to get the comma-and-space at the end  
  37.                     terms.push("");  
  38.                     this.value = terms.join(", ");  
  39.                     return false;  
  40.                 }  
  41.             });  
  42.         })  
  43.     </script> 

Step 8

Design view with HTML, cshtml and Bootstrap 4 classes,

Complete index view code

  1. @{  
  2.     Layout = null;  
  3. }  
  4.   
  5. <!DOCTYPE html>  
  6.   
  7. <html>  
  8. <head>  
  9.     <meta name="viewport" content="width=device-width" />  
  10.     <title>Index</title>  
  11.     <link href="~/Content/bootstrap.min.css" rel="stylesheet" />  
  12.     <script src="~/scripts/bootstrap.min.js"></script>  
  13.     <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">  
  14.     <link rel="stylesheet" href="/resources/demos/style.css">  
  15.     <script src="https://code.jquery.com/jquery-1.12.4.js"></script>  
  16.     <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>  
  17.     <script type="text/javascript">  
  18.         $(function () {  
  19.   
  20.             function split(val) {  
  21.                 return val.split(/,\s*/);  
  22.             }  
  23.             function extractLast(term) {  
  24.                 return split(term).pop();  
  25.             }  
  26.   
  27.             $("#myAutocomplete")  
  28.           // don't navigate away from the field on tab when selecting an item  
  29.           .on("keydown"function (event) {  
  30.               if (event.keyCode === $.ui.keyCode.TAB &&  
  31.                   $(this).autocomplete("instance").menu.active) {  
  32.                   event.preventDefault();  
  33.               }  
  34.           })  
  35.             .autocomplete({  
  36.                 minLength: 0,  
  37.                 source: function (request, response) {  
  38.                     $.getJSON('@Url.Action("Search","Home")', {  
  39.                         term: extractLast(request.term)  
  40.                     }, response);  
  41.                 },  
  42.                 focus: function () {  
  43.                     // prevent value inserted on focus  
  44.                     return false;  
  45.                 },  
  46.                 select: function (event, ui) {  
  47.                     var terms = split(this.value);  
  48.                     // remove the current input  
  49.                     terms.pop();  
  50.                     // add the selected item  
  51.                     terms.push(ui.item.value);  
  52.                     // add placeholder to get the comma-and-space at the end  
  53.                     terms.push("");  
  54.                     this.value = terms.join(", ");  
  55.                     return false;  
  56.                 }  
  57.             });  
  58.         })  
  59.     </script>  
  60. </head>  
  61. <body>  
  62.     <div class="container py-5">  
  63.         <div class="row">  
  64.             <div class="col-sm-6 col-md-6 col-xs-12">  
  65.                 <div class="form-group">  
  66.                     <label>Search Skills</label>  
  67.                     <input id="myAutocomplete" type="text" class="form-control">  
  68.                 </div>  
  69.             </div>  
  70.         </div>  
  71.     </div>  
  72. </body>  
  73. </html>  

Step 9

Run Project ctrl+F5,

Screenshot 1

ASP.NET

Screenshot 2

ASP.NET

Screenshot 3

ASP.NET

Screenshot 4

ASP.NET