Comma Separated AutoComplete TextBox In ASP.NET MVC

In this article, we will learn how to make comma separated autocomplete TextBox .

Background
 
Many times, we need to add comma separated values in a text box from autocomplete TextBox to fulfill the particular requirement.  Let's say, we have one page to send the emails. Then consider, we want to send emails to multiple recipients with cc and email Ids from coming from database using autocomplete TextBox. In this type of scenario, we need a comma separated autocomplete TextBox .Let's start implementing this scenario by creating one simple ASP.NET MVC application, step by step .
 
  1. Go to "Start" --> "All Programs"  --> select "Microsoft Visual Studio 2015".

  2. Go to "File" --> "New" --> click "Project" --> select "ASP.NET Web Application Template". Then, provide the project a name as you wish and click OK. After clicking, the following window will appear:

    new
Step 2: Create Model Class

Now, let us create the model class file named EmployeeModel.cs by right clicking on "Models" folder, as in the following screenshot:
 
Create Model Class
Now, the EmployeeModel.cs class file code snippet will look like this:
 
EmployeeModel.cs
  1. using System.ComponentModel.DataAnnotations;  
  2.   
  3. namespace CommaSepratedAutoCompleteTextBox.Models  
  4. {  
  5.     public class EmployeeModel  
  6.     {  
  7.         public int EmpId { getset; }  
  8.         public string EmpName { getset; }  
  9.   
  10.     }  

Step 3: Add Controller Class

Now, add the MVC 5 controller, as in the following screenshot:
 
Add Controller Class
After clicking on Add button, it will show the window. Specify the Controller name as Home with suffix Controller.

Note: 
The controller name must have a suffix as 'Controller'.

Now, modify the default code in HomeController.cs class file and create two action methods, after modifying the code it will look like the following: 

HomeController.cs
  1. using CommaSepratedAutoCompleteTextBox.Models;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web.Mvc;  
  5.   
  6. namespace CommaSepratedAutoCompleteTextBox.Controllers  
  7. {  
  8.     public class HomeController : Controller  
  9.     {  
  10.   
  11.         // GET: Home  
  12.         public ActionResult EmpoyeeDetails()  
  13.         {  
  14.             return View();  
  15.         }  
  16.   
  17.   
  18.         [HttpPost]  
  19.         public JsonResult GetAutoEmpName(string Prefix)  
  20.         {  
  21.   
  22.             //Adding list of records into list  
  23.             List<EmployeeModel> ObjList = new List<EmployeeModel>()  
  24.             {  
  25.                 new EmployeeModel {EmpId=1,EmpName="Vithal Wadje" },  
  26.                 new EmployeeModel {EmpId=2,EmpName="Suhir Wadje" },  
  27.                 new EmployeeModel {EmpId=3,EmpName="Anil Kumar" },  
  28.                 new EmployeeModel {EmpId=4,EmpName="Ravi" },  
  29.                 new EmployeeModel {EmpId=5,EmpName="Ramesh s" },  
  30.                 new EmployeeModel {EmpId=6,EmpName="Sachin Y" },  
  31.                 new EmployeeModel {EmpId=7,EmpName="Vikran T"},  
  32.                   
  33.   
  34.         };  
  35.             //Searching records from list using LINQ query.   
  36.             var EmpName = (from e in ObjList  
  37.                             where e.EmpName.ToLower().StartsWith(Prefix.ToLower())  
  38.                            select new { e.EmpName });  
  39.             return Json(EmpName, JsonRequestBehavior.AllowGet);  
  40.         }  
  41.   
  42.     }  

In the preceding code, instead of going to database for records, we are creating the generic list from model class and we will fetch records from above generic list. We can get the same records from database as well.
 
Step 4: Add Reference of  jQuery UI CSS and JS library
 
There are many ways to add the reference of jQuery library into our project. The following are some methods:
  1. Using NuGet package manager, you can install library and reference into the project.
  2. Use CDN library provided by Microsoft, jQuery, Google or any other which requires active internet connection.
  3. Download jQuery files from jQuery official website and reference into the project.

In the preceding procedure of adding references of libraries into the project, 1 & 3 steps don't require the active internet connection but if you are following the second step, it requires active internet connection to load the CDN library's references into the project .

In this example, I have followed the third step to add the jQuery UI libraries references. Now, open the Layout.cshtml page to add the references. The Layout.cshtml page's header section will be look like:
 
Layout.cshtml
  1. @*Uncomment following lines, If you wants to use CDN jquery-ui.css and jquery-ui.js*@  
  2.    @*<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">*@  
  3.    @*<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>*@  
  4.      
  5.    <script src="~/Scripts/jquery-1.10.2.min.js"></script>  
  6.    <link href="~/Content/jquery-ui.css" rel="stylesheet" />  
  7.    <script src="~/Scripts/jquery-ui.js"></script>
  8.  
Step 5: Create jQuery Ajax function.
 
To call controller JSON action method and invoke autocomplete function including for comma separated search text, write the following jQuery function .
  1. <script type="text/javascript">  
  2.   
  3.     $(document).ready(function () {  
  4.   
  5.          
  6.         $("#EmpName").autocomplete({  
  7.             source: function (req, resp) {  
  8.                 $.ajax({  
  9.                     url: "/Home/GetAutoEmpName",  
  10.                     type: "POST",  
  11.                     dataType: "json",  
  12.                     data: { Prefix: GetCurrentSearchTerm(req.term) },  
  13.                     success: function (data) {  
  14.                         resp($.map(data, function (item) {  
  15.                             return { label: item.EmpName, value: item.EmpName };  
  16.                         }))  
  17.   
  18.                     }  
  19.                 })  
  20.             },  
  21.             
  22.             select: function (event, ui) {  
  23.                 var LastValue = splitCurrentText(this.value);                
  24.                 LastValue.pop();  
  25.                 LastValue.push(ui.item.value);  
  26.                 LastValue.push("");  
  27.                 this.value = LastValue.join(",");  
  28.                 return false;  
  29.             },  
  30.             focus: function () {  
  31.             return false;  
  32.         }  
  33.         });  
  34.         function splitCurrentText(LastTerm) {  
  35.   
  36.             return LastTerm.split(/,\s*/);  
  37.         }  
  38.   
  39.         function GetCurrentSearchTerm(LastTerm) {  
  40.   
  41.             return splitCurrentText(LastTerm).pop();  
  42.         }  
  43.     });  
  44. </script> 
Note: To work preceding function, don't forget to add the reference of the following jQuery UI libraries into the project by CDN or by downloading.

Step 6: Create View

Now, let's create Strongly Typed View named EmployeeDetails from EmployeeModel class.

Create View
After adding the necessary code, files, and logic, the EmployeeDetails .cshtml will look like the following:
  1. @model CommaSepratedAutoCompleteTextBox.Models.EmployeeModel  
  2.   
  3. @{  
  4.     ViewBag.Title = "www.compilemode.com";  
  5. }  
  6. <script type="text/javascript">  
  7.   
  8.     $(document).ready(function () {  
  9.   
  10.          
  11.         $("#EmpName").autocomplete({  
  12.             source: function (req, resp) {  
  13.                 $.ajax({  
  14.                     url: "/Home/GetAutoEmpName",  
  15.                     type: "POST",  
  16.                     dataType: "json",  
  17.                     data: { Prefix: GetCurrentSearchTerm(req.term) },  
  18.                     success: function (data) {  
  19.                         resp($.map(data, function (item) {  
  20.                             return { label: item.EmpName, value: item.EmpName };  
  21.                         }))  
  22.   
  23.                     }  
  24.                 })  
  25.             },  
  26.             
  27.             select: function (event, ui) {  
  28.                 var LastValue = splitCurrentText(this.value);                
  29.                 LastValue.pop();  
  30.                 LastValue.push(ui.item.value);  
  31.                 LastValue.push("");  
  32.                 this.value = LastValue.join(",");  
  33.                 return false;  
  34.             },  
  35.             focus: function () {  
  36.             return false;  
  37.         }  
  38.         });  
  39.         function splitCurrentText(LastTerm) {  
  40.   
  41.             return LastTerm.split(/,\s*/);  
  42.         }  
  43.   
  44.         function GetCurrentSearchTerm(LastTerm) {  
  45.   
  46.             return splitCurrentText(LastTerm).pop();  
  47.         }  
  48.     });  
  49. </script>  
  50.   
  51. @using (Html.BeginForm())   
  52. {    
  53.     <div class="form-horizontal">  
  54.      <hr />  
  55.         <div class="form-group">  
  56.               
  57.             <div class="col-md-10">  
  58.                 @Html.EditorFor(model => model.EmpName, new { htmlAttributes = new { @class = "form-control" } })  
  59.             </div>  
  60.         </div>  
  61.   
  62.     </div>  

Now, run the application. Type any word and it will auto populate the records which exactly starts with the first word, as in the following screenshot:

output
Now, after selecting the particular records, it is added into TextBox with comma. Now, type another initial letter and it will popup the list of records. 

output 
Now, add multiple records with commas. The TextBox will look like as follows.

output
From all preceding examples and explanations, I hope you learned how to create the comma separated auto complete TextBox using jQuery UI in ASP.NET MVC.
 
Note
  • Download the Zip file of the sample application for a better understanding.
  • Since this is a demo, it might not be using proper standards. So, improve it according to your skills.
Summary

I hope this article is useful for all the readers. If you have any suggestions, please contact me.

Read more articles on ASP.NET