Add Item In Kendo MultiSelect Using ASP.NET WEB API And Entity Framework

Introduction

Kendo MultiSelect is one of the widgets from Kendo UI package. This article explains how to implement the add new Item functionality in Kendo MultiSelect control, using ASP.NET WEB API and Entity Framework. To explain it, I have created a RESTful GET Service, using ASP.NET WEB API, which is used to load the DataSource of Kendo MultiSelect.

Prerequisites

Basic knowledge of ASP.NET Web API, jQuery and Kendo UI.

Content

  1. Creating an ASP.NET WEB API Application.
  2. Creating a Model.
  3. Creating a Context in an Entity Framework.
  4. Creating a Controller.
  5. Adding a new item in Kendo MultiSelect control. 

Creating an ASP.NET Web API Application

Create a Web API Application, using an installed Web template in Visual Studio, as shown below. In my case, I named the Application “KendoMultiSelect”.
 
  
 
Figure 1
 
  
 
 Figure 2
 
 
Creating a Model
 
  In Solution Explorer, right click the Models folder, select Add, followed by class and name it as Technology.cs. 
 
Technology.cs 
  1. public class Technology  
  2.    {  
  3.        [Key]  
  4.        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]  
  5.        public int Value { getset; }  
  6.        public string Text { getset; }  
  7.    }  
Creating a context 

Create a new folder in the project and name it as DAL . Right click on DAL folder, add new class and name it as TechnologyContext.cs, which is given below.  
  1. public class TechnologyContext:DbContext  
  2.    {       
  3.            public TechnologyContext()  
  4.              : base("TechnologyConnection")  
  5.            {  
  6.                Database.SetInitializer<TechnologyContext>(new CreateDatabaseIfNotExists<TechnologyContext>());  
  7.                 
  8.            }  
  9.   
  10.            public DbSet<Technology> Technologies { getset; }  
  11.     
  12.    }  
Update the connection string in web.config file, which is given below. 
  1. <connectionStrings>  
  2.    <add name="TechnologyConnection" connectionString="Data Source=DESKTOP-585QGBN;Initial Catalog=Employee;Integrated Security=True" providerName="System.Data.SqlClient" />  
  3.   </connectionStrings>  
Creating a Controller 
 
Right click on the Controller folder and add a new Web API 2- Empty controller, as shown in the figure 3. In my case, I named it as TechnologiesController.
 
 
Figure 3
 
TechnologiesController.cs 
  1. using System.Linq;  
  2. using System.Web.Http;  
  3. using System.Web.Http.Description;  
  4. using KendoMultiSelect.DAL;  
  5. using KendoMultiSelect.Models;  
  6.   
  7. namespace KendoMultiSelect.Controllers  
  8. {  
  9.     public class TechnologiesController : ApiController  
  10.     {  
  11.         private TechnologyContext db = new TechnologyContext();  
  12.   
  13.         // GET: api/Technologies  
  14.         public IQueryable<Technology> GetTechnologies()  
  15.         {  
  16.             return db.Technologies;  
  17.         }  
  18.   
  19.          
  20.         // POST: api/Technologies  
  21.         [ResponseType(typeof(Technology))]  
  22.         public IHttpActionResult PostTechnology(Technology technology)  
  23.         {  
  24.             if (!ModelState.IsValid)  
  25.             {  
  26.                 return BadRequest(ModelState);  
  27.             }  
  28.   
  29.             db.Technologies.Add(technology);  
  30.             db.SaveChanges();  
  31.   
  32.             return CreatedAtRoute("DefaultApi"new { id = technology.Value }, technology);  
  33.         }  
  34.   
  35.          
  36.         protected override void Dispose(bool disposing)  
  37.         {  
  38.             if (disposing)  
  39.             {  
  40.                 db.Dispose();  
  41.             }  
  42.             base.Dispose(disposing);  
  43.         }  
  44.   
  45.          
  46.     }  
  47. }  
Now, API's are ready. Let's start to implement the Add new item functioanlity in Kendo MultiSelect control.  
 
Remote data binding in Kendo MultiSelect control and adding a new item
 
Create a new HTML page in our Application. In my case, I named it as kendoMultiSelect.html
 
KendoMultiSelect.html 
  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4.     <title>Kendo Multi Select</title>  
  5.     <meta charset="utf-8" />  
  6.     <link rel="stylesheet" href="http://kendo.cdn.telerik.com/2017.1.118/styles/kendo.common.min.css">  
  7.     <link rel="stylesheet" href="http://kendo.cdn.telerik.com/2017.1.118/styles/kendo.rtl.min.css">  
  8.     <link rel="stylesheet" href="http://kendo.cdn.telerik.com/2017.1.118/styles/kendo.default.min.css">  
  9.     <link rel="stylesheet" href="http://kendo.cdn.telerik.com/2017.1.118/styles/kendo.mobile.all.min.css">  
  10.   
  11.     <script src="http://code.jquery.com/jquery-1.12.3.min.js"></script>  
  12.     <script src="http://kendo.cdn.telerik.com/2017.1.118/js/angular.min.js"></script>  
  13.     <script src="http://kendo.cdn.telerik.com/2017.1.118/js/jszip.min.js"></script>  
  14.     <script src="http://kendo.cdn.telerik.com/2017.1.118/js/kendo.all.min.js"></script>  
  15. </head>  
  16. <body>  
  17.     <h3> Kendo Multi Select</h3>  
  18.     <div class="demo-section k-content">  
  19.         <select id="technologies" data-placeholder="Select Technology..."></select>  
  20.     </div>  
  21.     <script id="noDataTemplate" type="text/x-kendo-template">  
  22.         <div>  
  23.             No data found. Do you want to add new item - '#: instance.input.val() #' ?  
  24.         </div>  
  25.         <br />  
  26.         <button class="k-button" onclick="addNew('#: instance.element[0].id #', '#: instance.input.val() #')">Add new item</button>  
  27.     </script>  
  28.     <script>  
  29.         $(document).ready(function () {  
  30.   
  31.             var dataSource = new kendo.data.DataSource({  
  32.                 transport: {  
  33.                     read: {  
  34.                         url: "api/Technologies",  
  35.                         dataType: "json"  
  36.                     },  
  37.                     create: {  
  38.                         url: "api/Technologies",  
  39.                         type:"POST",  
  40.                         dataType: "json",  
  41.   
  42.                         parameterMap: function(options, operation) {  
  43.                             if (operation !== "read" && options.models) {  
  44.                                 return {models: kendo.stringify(options.models)};  
  45.                             }  
  46.                         }  
  47.         },  
  48.                     },  
  49.                     schema: {  
  50.                         model: {  
  51.                             id: "Value",  
  52.                             fields: {  
  53.                                 Value: { type: "number" },  
  54.                                 Text: { type: "string" }  
  55.                             }  
  56.                         }  
  57.                     }  
  58.                 });  
  59.                 $("#technologies").kendoMultiSelect({  
  60.                     filter: "startswith",  
  61.                     dataTextField: "Text",  
  62.                     dataValueField: "Value",  
  63.                     dataSource: dataSource,  
  64.                     noDataTemplate: kendo.template($("#noDataTemplate").html())  
  65.                 });  
  66.             });  
  67.             function addNew(widgetId, value) {  
  68.                  
  69.                 var widget = $("#" + widgetId).getKendoMultiSelect();  
  70.                 var dataSource = widget.dataSource;  
  71.   
  72.                 if (confirm("Are you sure?")) {  
  73.                     dataSource.add({  
  74.                         Value: 0,  
  75.                         Text: value  
  76.                     });  
  77.   
  78.                     dataSource.one("requestEnd", function (args) {  
  79.                         if (args.type !== "create") {  
  80.                             return;  
  81.                         }  
  82.   
  83.                         var newValue = args.response[0].Value;  
  84.   
  85.                         dataSource.one("sync", function () {  
  86.                             widget.value(widget.value().concat([newValue]));  
  87.                         });  
  88.                     });  
  89.   
  90.                     dataSource.sync();  
  91.                 }  
  92.             }  
  93.   
  94.     </script>  
  95. </body>  
  96. </html>  
From the code given above, we can observe the points given below.
  1. The no Data template is created, where the respective HTML template will render, if there is no item in Kendo MultiSelect, which we have discussed in my previous article

  2. In the no data template, we have the Add new item button, while clicking on it; it will fire the addNew function, which will call the POST API to insert the newly entered record.
Result in Browser
 
Initially, there is no record in our Kendo MultiSelect control to display. 
 
 
 Figure 4
 
Enter some text in the control. In my case, I entered C#, which is not in the list, so it will render the no data template. Now, click Add new item button to add C# in the list and you will get the confirmation alert. Click OK to save the text.  
 
 
Now, C# is added successfully in the list  
 
Figure 5
 
Updated SQL table
 
  
 
 Figure 6 
 
Reference
  • http://docs.telerik.com/kendo-ui/api/javascript/ui/multiselect
I hope, you have enjoyed this article. Your valuable feedback, questions or comments about this article are always welcome.

Up Next
    Ebook Download
    View all
    Learn
    View all