TagIt Control With Data From Database Using AngularJS In MVC Web API

In this article we will learn how to load the tags fromthe database in ASP.NET MVC Web API using AngularJS. Here we are going to use a pretty control called tagIt which does the tag part easier with a lot of configuration options. This article uses a normal MVC application which includes the Web API control in it; in addition to it, we use AngularJS for our client-side operations. Please see the links given below if you are new to these technologies.

As the article title implies, we are actually going to load the tags from a table called tblTags from SQL Server database. So now we will go and create our application. I hope you will like this.

Download the source code

You can always download the source code here: Load Tags From Database Using Angular JS In MVC Web API

Background

A few days back I was trying to use the tagIt widget in one of my applications. I could do that with some pre-defined tags as a variable. Then I thought why don’t we try something like loading these tags from the database? Hence my application uses MVC architecture; I selected Web API for retrieving the data fromthe database. I hope someone finds this useful.

Create a MVC application

Click File-> New-> Project then select MVC application. Before going to start the coding part, make sure that all the required extensions/references are installed. Below are the required things to start with.

  • AngularJS
  • TagIt Plugin
  • jQuery

You can download all the items mentioned above from NuGet. Right click on your project name and select Manage NuGet packages.

Manage NuGet Package Window

Once you have installed those items, please make sure that all the items(jQuery, Angular JS files, Tag It JS files like tag-it.js) are loaded in your scripts folder.

Using the code

Before going to load the tags from a database we will try to load our tagit control with some predefined array values. No worries, later we will change this array values to the values we get from the database.

Include the references in your _Layout.cshtml.

As we have already installed all the packages we need, now we need to add the references, right?

  1. @RenderBody()  
  2. @Scripts.Render("~/bundles/jquery")  
  3. <script src="~/Scripts/jquery-2.2.0.js"></script>  
  4. <script src="~/Content/jquery-ui.min.js"></script>  
  5. <script src="~/Scripts/angular.js"></script>  
  6. <script src="~/Scripts/angular-route.js"></script>  
  7. <script src="~/Scripts/tag-it.min.js"></script>  
  8. <script src="~/Scripts/MyScripts/TagScripts.js"></script>  
  9. @RenderSection("scripts", required: false)   

Here TagScripts.js is the JavaScript file where we are going to write our own scripts.

Set the changes in View

So we have added the references, now we will make the changes in our view. As we uses Angular JS, we will set our ng-app and ng-controller as follows.

  1. <div ng-app="tagApp">  
  2.     <div ng-controller="tagController">  
  3.         <ul id="tags"></ul>  
  4.         <div id="error">Nothing found!</div>  
  5.     </div>  
  6. </div>   

You can give a style as follows if you want.

  1. <style>  
  2. #tags {  
  3.     width: 25%;  
  4. }  
  5.  
  6. #error {  
  7.     display: none;  
  8.     font-weight: bold;  
  9.     color: #1c94c4;  
  10.     font-family: Trebuchet MS, Tahoma, Verdana, Arial, sans-serif;  
  11.     font-size: 1.1em;  
  12. }  
  13. </style>   

Oops!, I forgot to mention, please do not forget to include the CSS style sheets.

  1. <link href="~/Content/jquery-ui.css" rel="stylesheet" />  
  2. <link href="~/Content/jquery.tagit.css" rel="stylesheet" />   

Now we can write the scripts in our TagScripts.js file.

Create Angular App

You can create an Angular module as follows.

  1. var app;  
  2. //Angular App  
  3. app = angular.module('tagApp', []);   

Here the module name must be same as we have given in ng-app in our view.

Create Angular Controller

You can create an Angular Controller as follows.app.controller('tagController', function($scope)  

  1. {  
  2.     $("#tags").tagit(  
  3.     {  
  4.         availableTags: availableTags,  
  5.         autocomplete:  
  6.         {  
  7.             delay: 0,  
  8.             minLength: 1  
  9.         },  
  10.         beforeTagAdded: function(event, ui)  
  11.         {  
  12.             if ($.inArray(ui.tagLabel, availableTags) < 0)  
  13.             {  
  14.                 $('#error').show();  
  15.                 return false;  
  16.             }  
  17.             else  
  18.             {  
  19.                 $('#error').hide();  
  20.             }  
  21.         }  
  22.     });  
  23. });  

As you can see we have called tagit() function to initialize the tagit control. Below are the explanations to the options we have given.

  • availableTags

    availableTags are the source we need to apply to the control so that the given items can be shown on user actions.

  • autocomplelte

    autocomplete is a property which enables the auto complete option, when it is true user will get the items listed accordingly for each key press

  • beforeTagAdded

    beforeTagAdded is a callback function which gets fired before we add the new tags to the control. This function can be used to do all the needed tasks before adding the given item to the control. For example, if we need to load only the values from the database and if we need to restrict creating the new tags by the user, means user will be allowed to use only the available tags which is in the available tag array. The preceding code block does what has been explained above.
  1. if ($.inArray(ui.tagLabel, availableTags) < 0)  
  2. {  
  3.     $('#error').show();  
  4.     return false;  
  5. }  
  6. else  
  7. {  
  8.     $('#error').hide();  
  9. }   

If user tries to add a new tag, we will show the alert div which we already set in our view.

Now it is time to see the control in our view, let us see whether it works fine, if not, we may need to go back and check again.

Tag_It_Control_Defined_Array

Tag_It_Control_Defined_Array

Tag_It_Control_Defined_Array_If_Nothing_Found

Tag_It_Control_Defined_Array_If_Nothing_Found

It seems everything is fine, thank god we don’t need any debugging :)

Now we will create a Web API controller. Oh yeah, we are going to start our real coding. Right click on your controller folder and click new.

Web_API_controller

So our Web API controller is ready, then it is time to go to do some AngularJS scripts, don’t worry we will come back here.

We need to make changes to our AngularJS controller tagController as follows.

  1. //Angular Controller  
  2. app.controller('tagController', function($scope, tagService)  
  3. {  
  4.     //Angular service call  
  5.     var tgs = tagService.getTags();  
  6.     if (tgs != undefined)  
  7.     {  
  8.         tgs.then(function(d)  
  9.         {  
  10.             availableTags = [];  
  11.             for (var i = 0; i < d.data.length; i++)  
  12.             {  
  13.                 availableTags.push(d.data[i].tagName);  
  14.             }  
  15.             $("#tags").tagit(  
  16.             {  
  17.                 availableTags: availableTags,  
  18.                 autocomplete:  
  19.                 {  
  20.                     delay: 0,  
  21.                     minLength: 1  
  22.                 },  
  23.                 beforeTagAdded: function(event, ui)  
  24.                 {  
  25.                     if ($.inArray(ui.tagLabel, availableTags) < 0)  
  26.                     {  
  27.                         $('#error').show();  
  28.                         return false;  
  29.                     }  
  30.                     else  
  31.                     {  
  32.                         $('#error').hide();  
  33.                     }  
  34.                 }  
  35.             });  
  36.             console.log(JSON.stringify(availableTags));  
  37.         }, function(error)  
  38.         {  
  39.             console.log('Oops! Something went wrong while fetching the data.');  
  40.         });  
  41.     }  
  42. });   

As you have noticed, we are calling an AngularJS service here. Once we get the data from the service, we are assigning it to the array which we have initialized with the predefined values, so that the data from the database will be available in the tagit control. So can we create our AngularJS service?

  1. //Angular Service  
  2. app.service('tagService'function($http)  
  3. {  
  4.     //call the web api controller  
  5.     this.getTags = function()  
  6.     {  
  7.         return $http(  
  8.         {  
  9.             method: 'get',  
  10.             url: 'api/tag'  
  11.         });  
  12.     }  
  13. });   

This will fire our Web API controller and action GET api/tag. And the Web API controller will give you the results which we will format again and give to the available tag array. Sounds cool? Wait, we can do all these things without AngularJS, meaning we can simply call a jQuery Ajax Get. Do you want to see how? Here it is.

  1. USE[master]  
  2. GO  
  3. /****** Object: Database [TrialsDB] Script Date: 17-Feb-16 10:21:17 PM ******/  
  4. CREATE DATABASE[TrialsDB]  
  5. CONTAINMENT = NONE  
  6. ON PRIMARY(NAME = N 'TrialsDB', FILENAME = N 'C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\TrialsDB.mdf'SIZE = 3072 KB, MAXSIZE = UNLIMITED, FILEGROWTH = 1024 KB)  
  7. LOG ON(NAME = N 'TrialsDB_log', FILENAME = N 'C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\TrialsDB_log.ldf'SIZE = 1024 KB, MAXSIZE = 2048 GB, FILEGROWTH = 10 % )  
  8. GO  
  9. ALTER DATABASE[TrialsDB] SET COMPATIBILITY_LEVEL = 110  
  10. GO  
  11. IF(1 = FULLTEXTSERVICEPROPERTY('IsFullTextInstalled'))  
  12. begin  
  13. EXEC[TrialsDB].[dbo].[sp_fulltext_database] @action = 'enable'  
  14. end  
  15. GO  
  16. ALTER DATABASE[TrialsDB] SET ANSI_NULL_DEFAULT OFF  
  17. GO  
  18. ALTER DATABASE[TrialsDB] SET ANSI_NULLS OFF  
  19. GO  
  20. ALTER DATABASE[TrialsDB] SET ANSI_PADDING OFF  
  21. GO  
  22. ALTER DATABASE[TrialsDB] SET ANSI_WARNINGS OFF  
  23. GO  
  24. ALTER DATABASE[TrialsDB] SET ARITHABORT OFF  
  25. GO  
  26. ALTER DATABASE[TrialsDB] SET AUTO_CLOSE OFF  
  27. GO  
  28. ALTER DATABASE[TrialsDB] SET AUTO_CREATE_STATISTICS ON  
  29. GO  
  30. ALTER DATABASE[TrialsDB] SET AUTO_SHRINK OFF  
  31. GO  
  32. ALTER DATABASE[TrialsDB] SET AUTO_UPDATE_STATISTICS ON  
  33. GO  
  34. ALTER DATABASE[TrialsDB] SET CURSOR_CLOSE_ON_COMMIT OFF  
  35. GO  
  36. ALTER DATABASE[TrialsDB] SET CURSOR_DEFAULT GLOBAL  
  37. GO  
  38. ALTER DATABASE[TrialsDB] SET CONCAT_NULL_YIELDS_NULL OFF  
  39. GO  
  40. ALTER DATABASE[TrialsDB] SET NUMERIC_ROUNDABORT OFF  
  41. GO  
  42. ALTER DATABASE[TrialsDB] SET QUOTED_IDENTIFIER OFF  
  43. GO  
  44. ALTER DATABASE[TrialsDB] SET RECURSIVE_TRIGGERS OFF  
  45. GO  
  46. ALTER DATABASE[TrialsDB] SET DISABLE_BROKER  
  47. GO  
  48. ALTER DATABASE[TrialsDB] SET AUTO_UPDATE_STATISTICS_ASYNC OFF  
  49. GO  
  50. ALTER DATABASE[TrialsDB] SET DATE_CORRELATION_OPTIMIZATION OFF  
  51. GO  
  52. ALTER DATABASE[TrialsDB] SET TRUSTWORTHY OFF  
  53. GO  
  54. ALTER DATABASE[TrialsDB] SET ALLOW_SNAPSHOT_ISOLATION OFF  
  55. GO  
  56. ALTER DATABASE[TrialsDB] SET PARAMETERIZATION SIMPLE  
  57. GO  
  58. ALTER DATABASE[TrialsDB] SET READ_COMMITTED_SNAPSHOT OFF  
  59. GO  
  60. ALTER DATABASE[TrialsDB] SET HONOR_BROKER_PRIORITY OFF  
  61. GO  
  62. ALTER DATABASE[TrialsDB] SET RECOVERY FULL  
  63. GO  
  64. ALTER DATABASE[TrialsDB] SET MULTI_USER  
  65. GO  
  66. ALTER DATABASE[TrialsDB] SET PAGE_VERIFY CHECKSUM  
  67. GO  
  68. ALTER DATABASE[TrialsDB] SET DB_CHAINING OFF  
  69. GO  
  70. ALTER DATABASE[TrialsDB] SET FILESTREAM(NON_TRANSACTED_ACCESS = OFF)  
  71. GO  
  72. ALTER DATABASE[TrialsDB] SET TARGET_RECOVERY_TIME = 0 SECONDS  
  73. GO  
  74. ALTER DATABASE[TrialsDB] SET READ_WRITE  
  75. GO   

Now the only thing pending is to get the data from our API controller, we will see that part now. For that first you must create a database and a table in it, right?

Create a database

The following query can be used to create a database in your SQL Server.

  1. USE [master]  
  2. GO  
  3. /****** Object: Database [TrialsDB] Script Date: 17-Feb-16 10:21:17 PM ******/  
  4. CREATE DATABASE [TrialsDB]  
  5. CONTAINMENT = NONE  
  6. ON PRIMARY  
  7. NAME = N'TrialsDB', FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\TrialsDB.mdf' , SIZE = 3072KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )  
  8. LOG ON  
  9. NAME = N'TrialsDB_log', FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\TrialsDB_log.ldf' , SIZE = 1024KB , MAXSIZE = 2048GB , FILEGROWTH = 10%)  
  10. GO  
  11. ALTER DATABASE [TrialsDB] SET COMPATIBILITY_LEVEL = 110  
  12. GO  
  13. IF (1 = FULLTEXTSERVICEPROPERTY('IsFullTextInstalled'))  
  14. begin  
  15. EXEC [TrialsDB].[dbo].[sp_fulltext_database] @action = 'enable'  
  16. end  
  17. GO  
  18. ALTER DATABASE [TrialsDB] SET ANSI_NULL_DEFAULT OFF  
  19. GO  
  20. ALTER DATABASE [TrialsDB] SET ANSI_NULLS OFF  
  21. GO  
  22. ALTER DATABASE [TrialsDB] SET ANSI_PADDING OFF  
  23. GO  
  24. ALTER DATABASE [TrialsDB] SET ANSI_WARNINGS OFF  
  25. GO  
  26. ALTER DATABASE [TrialsDB] SET ARITHABORT OFF  
  27. GO  
  28. ALTER DATABASE [TrialsDB] SET AUTO_CLOSE OFF  
  29. GO  
  30. ALTER DATABASE [TrialsDB] SET AUTO_CREATE_STATISTICS ON  
  31. GO  
  32. ALTER DATABASE [TrialsDB] SET AUTO_SHRINK OFF  
  33. GO  
  34. ALTER DATABASE [TrialsDB] SET AUTO_UPDATE_STATISTICS ON  
  35. GO  
  36. ALTER DATABASE [TrialsDB] SET CURSOR_CLOSE_ON_COMMIT OFF  
  37. GO  
  38. ALTER DATABASE [TrialsDB] SET CURSOR_DEFAULT GLOBAL  
  39. GO  
  40. ALTER DATABASE [TrialsDB] SET CONCAT_NULL_YIELDS_NULL OFF  
  41. GO  
  42. ALTER DATABASE [TrialsDB] SET NUMERIC_ROUNDABORT OFF  
  43. GO  
  44. ALTER DATABASE [TrialsDB] SET QUOTED_IDENTIFIER OFF  
  45. GO  
  46. ALTER DATABASE [TrialsDB] SET RECURSIVE_TRIGGERS OFF  
  47. GO  
  48. ALTER DATABASE [TrialsDB] SET DISABLE_BROKER  
  49. GO  
  50. ALTER DATABASE [TrialsDB] SET AUTO_UPDATE_STATISTICS_ASYNC OFF  
  51. GO  
  52. ALTER DATABASE [TrialsDB] SET DATE_CORRELATION_OPTIMIZATION OFF  
  53. GO  
  54. ALTER DATABASE [TrialsDB] SET TRUSTWORTHY OFF  
  55. GO  
  56. ALTER DATABASE [TrialsDB] SET ALLOW_SNAPSHOT_ISOLATION OFF  
  57. GO  
  58. ALTER DATABASE [TrialsDB] SET PARAMETERIZATION SIMPLE  
  59. GO  
  60. ALTER DATABASE [TrialsDB] SET READ_COMMITTED_SNAPSHOT OFF  
  61. GO  
  62. ALTER DATABASE [TrialsDB] SET HONOR_BROKER_PRIORITY OFF  
  63. GO  
  64. ALTER DATABASE [TrialsDB] SET RECOVERY FULL  
  65. GO  
  66. ALTER DATABASE [TrialsDB] SET MULTI_USER  
  67. GO  
  68. ALTER DATABASE [TrialsDB] SET PAGE_VERIFY CHECKSUM  
  69. GO  
  70. ALTER DATABASE [TrialsDB] SET DB_CHAINING OFF  
  71. GO  
  72. ALTER DATABASE [TrialsDB] SET FILESTREAM( NON_TRANSACTED_ACCESS = OFF )  
  73. GO  
  74. ALTER DATABASE [TrialsDB] SET TARGET_RECOVERY_TIME = 0 SECONDS  
  75. GO  
  76. ALTER DATABASE [TrialsDB] SET READ_WRITE  
  77. GO   

Now we will create a table.

Create table in database

Below is the query to create table in database.

  1. USE [TrialsDB]  
  2. GO  
  3. /****** Object: Table [dbo].[tblTags] Script Date: 17-Feb-16 10:22:00 PM ******/  
  4. SET ANSI_NULLS ON  
  5. GO  
  6. SET QUOTED_IDENTIFIER ON  
  7. GO  
  8. CREATE TABLE [dbo].[tblTags](  
  9. [tagId] [int] IDENTITY(1,1) NOT NULL,  
  10. [tagName] [nvarchar](50) NOT NULL,  
  11. [tagDescription] [nvarchar](maxNULL,  
  12. CONSTRAINT [PK_tblTags] PRIMARY KEY CLUSTERED  
  13. (  
  14. [tagId] ASC  
  15. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  16. ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]  
  17. GO 

Can we insert some data to the table now?

Insert data to table

You can use the following query to insert the data.

  1. USE [TrialsDB]  
  2. GO  
  3. INSERT INTO [dbo].[tblTags]  
  4. ([tagName]  
  5. ,[tagDescription])  
  6. VALUES  
  7. (<tagName, nvarchar(50),>  
  8. ,<tagDescription, nvarchar(max),>)  
  9. GO  

So, let us say, we have inserted the data as follows.

Insertion_In_Table

Next thing we are going to do is create a ADO.NET Entity Data Model.

Create Entity Data Model

Right click on your model folder and click new, select ADO.NET Entity Data Model. Follow the steps given. Once you have done the process, you can see the edmx file and other files in your model folder.

ADO_NET_Model_Entity

Then it is time to go back to our Web API controller. Please change the code as below.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Data;  
  4. using System.Data.Entity;  
  5. using System.Data.Entity.Infrastructure;  
  6. using System.Linq;  
  7. using System.Net;  
  8. using System.Net.Http;  
  9. using System.Web;  
  10. using System.Web.Http;  
  11. using Load_Tags_From_DB_Using_Angular_JS_In_MVC.Models;  
  12. namespace Load_Tags_From_DB_Using_Angular_JS_In_MVC.Controllers  
  13. {  
  14.     public class TagController: ApiController  
  15.     {  
  16.         private DBEntities db = new DBEntities();  
  17.         // GET api/Tag  
  18.         public IEnumerable < tblTag > Get()  
  19.         {  
  20.             return db.tblTags.AsEnumerable();  
  21.         }  
  22.     }  
  23. }   

Once this is done, we can say that we are finished with all steps. That’s fantastic, right? Now we will see the output.

Output
Load_Tags_From_Database_Output

Have a happy coding.

Conclusion

Did I miss anything that you may think is needed? Did you try Web API yet? Have you ever wanted to do this requirement? Did you find this post useful? I hope you liked this article. Please share with me your valuable suggestions and feedback.

Your turn. What do you think?

A blog isn’t a blog without comments, but do try to stay on topic. If you have a question unrelated to this post, you’re better off posting it on C# Corner, Code Project, Stack Overflow, Asp.Net Forum instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I can.

Please see this article in my blog here.

Read more articles on ASP.NET: