Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / HTML

TagIt Control With Data From Database Using Angular JS In MVC Web API

5.00/5 (4 votes)
25 Feb 2016CPOL6 min read 7.9K  
How to load the tags from database in MVC Web API using Angular JS

In this article, we will learn how to load the tags from database in MVC Web API using Angular JS. 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 use a normal MVC application which includes the Web API control in it, in addition to it, we use Angular JS for our client side operations. You can always get the tips/tricks/blogs about these mentioned technologies from the links given below:

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.

Background

Few days ago, 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 database. Hence my application uses MVC architecture, I selected Web API for retrieving the data from database. I hope someone will find this useful.

Create an 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:

  • Angular JS
  • TagIt Plugin
  • jQuery

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

Manage NuGet Package Window

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?

HTML
@RenderBody()

    @Scripts.Render("~/bundles/jquery")
    <script src="~/Scripts/jquery-2.2.0.js"></script>
    <script src="~/Content/jquery-ui.min.js"></script>
    <script src="~/Scripts/angular.js"></script>
    <script src="~/Scripts/angular-route.js"></script>
    <script src="~/Scripts/tag-it.min.js"></script>
    <script src="~/Scripts/MyScripts/TagScripts.js"></script>
    @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 use Angular JS, we will set our ng-app and ng-controller as follows:

HTML
<div ng-app="tagApp">
    <div ng-controller="tagController">
        <ul id="tags"></ul>
        <div id="error">Nothing found!</div>
    </div>
</div>

You can give a style as follows if you want.

CSS
<style>
    #tags {
        width: 25%;
    }

    #error {
        display:none;
        font-weight: bold;
        color: #1c94c4;
        font-family: Trebuchet MS,Tahoma,Verdana,Arial,sans-serif;
        font-size: 1.1em;
    }
</style>

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

HTML
<link href="~/Content/jquery-ui.css" rel="stylesheet" />
<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:

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

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

Create Angular Controller

You can create an Angular Controller as follows:

JavaScript
app.controller('tagController', function ($scope) {
        $("#tags").tagit({
            availableTags: availableTags,
            autocomplete: { delay: 0, minLength: 1 },
            beforeTagAdded: function (event, ui) {
                if ($.inArray(ui.tagLabel, availableTags) < 0) {
                    $('#error').show();
                    return false;
                } else {
                    $('#error').hide();
                }
            }
        });
    });

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.

  • autocomplete

    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.

    JavaScript
    if ($.inArray(ui.tagLabel, availableTags) < 0) {
                        $('#error').show();
                        return false;
                    } else {
                        $('#error').hide();
                    }

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

Web_API_controller

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

We need to make changes to our Angular JS controller tagController as follows:

JavaScript
//Angular Controller
app.controller('tagController', function ($scope, tagService) {
    //Angular service call
    var tgs = tagService.getTags();
    if (tgs != undefined) {
        tgs.then(function (d) {
            availableTags = [];
            for (var i = 0; i < d.data.length; i++) {
                availableTags.push(d.data[i].tagName);
            }

            $("#tags").tagit({
                availableTags: availableTags,
                autocomplete: { delay: 0, minLength: 1 },
                beforeTagAdded: function (event, ui) {
                    if ($.inArray(ui.tagLabel, availableTags) < 0) {
                        $('#error').show();
                        return false;
                    } else {
                        $('#error').hide();
                    }
                }
            });
            console.log(JSON.stringify(availableTags));
        }, function (error) {
            console.log('Oops! Something went wrong while fetching the data.');
        });
    }
});

As you have noticed, we are calling an Angular JS 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 Angular JS service?

JavaScript
//Angular Service
app.service('tagService', function ($http) {
    //call the web api controller
    this.getTags = function () {
        return $http({
            method: 'get',
            url: 'api/tag'
        });
    }
});

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 this stuff without Angular JS, means we can simply call a jQuery Ajax Get. Do you want to see how? Here it is.

JavaScript
/* Using jQuery */

$(function () {
    var availableTags = [
      "ActionScript",
      "AppleScript",
      "Asp",
      "BASIC",
      "C",
      "C++",
      "Clojure",
      "COBOL",
      "ColdFusion",
      "Erlang",
      "Fortran",
      "Groovy",
      "Haskell",
      "Java",
      "JavaScript",
      "Lisp",
      "Perl",
      "PHP",
      "Python",
      "Ruby",
      "Scala",
      "Scheme"
    ];   
    //Load the available tags from database start
    $.ajax({
        type: 'GET',
        dataType: 'json',
        contentType: 'application/json;charset=utf-8',
        url: 'http://localhost:56076/api/Tag',
        success: function (data) {
            try {
                if (data.length > 0) {
                    availableTags = data;
                }
            } catch (e) {
                console.log('Error while formatting the data : ' + e.message)
            }
        },
        error: function (xhrequest, error, thrownError) {
            console.log('Error while ajax call: ' + error)
        }
    });
    //Load the available tags from database end

    $("#tags").tagit({
        availableTags: availableTags,
        autocomplete: { delay: 0, minLength: 1 },
        beforeTagAdded: function (event, ui) {
            if ($.inArray(ui.tagLabel, availableTags) < 0) {
                $('#error').show();
                return false;
            } else {
                $('#error').hide();
            }
        }
    });
});

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.

SQL
USE [master]
GO

/****** Object:  Database [TrialsDB]    Script Date: 17-Feb-16 10:21:17 PM ******/
CREATE DATABASE [TrialsDB]
 CONTAINMENT = NONE
 ON  PRIMARY 
( NAME = N'TrialsDB', _
FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\TrialsDB.mdf' , _
SIZE = 3072KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )
 LOG ON 
( 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%)
GO

ALTER DATABASE [TrialsDB] SET COMPATIBILITY_LEVEL = 110
GO

IF (1 = FULLTEXTSERVICEPROPERTY('IsFullTextInstalled'))
begin
EXEC [TrialsDB].[dbo].[sp_fulltext_database] @action = 'enable'
end
GO

ALTER DATABASE [TrialsDB] SET ANSI_NULL_DEFAULT OFF 
GO

ALTER DATABASE [TrialsDB] SET ANSI_NULLS OFF 
GO

ALTER DATABASE [TrialsDB] SET ANSI_PADDING OFF 
GO

ALTER DATABASE [TrialsDB] SET ANSI_WARNINGS OFF 
GO

ALTER DATABASE [TrialsDB] SET ARITHABORT OFF 
GO

ALTER DATABASE [TrialsDB] SET AUTO_CLOSE OFF 
GO

ALTER DATABASE [TrialsDB] SET AUTO_CREATE_STATISTICS ON 
GO

ALTER DATABASE [TrialsDB] SET AUTO_SHRINK OFF 
GO

ALTER DATABASE [TrialsDB] SET AUTO_UPDATE_STATISTICS ON 
GO

ALTER DATABASE [TrialsDB] SET CURSOR_CLOSE_ON_COMMIT OFF 
GO

ALTER DATABASE [TrialsDB] SET CURSOR_DEFAULT  GLOBAL 
GO

ALTER DATABASE [TrialsDB] SET CONCAT_NULL_YIELDS_NULL OFF 
GO

ALTER DATABASE [TrialsDB] SET NUMERIC_ROUNDABORT OFF 
GO

ALTER DATABASE [TrialsDB] SET QUOTED_IDENTIFIER OFF 
GO

ALTER DATABASE [TrialsDB] SET RECURSIVE_TRIGGERS OFF 
GO

ALTER DATABASE [TrialsDB] SET  DISABLE_BROKER 
GO

ALTER DATABASE [TrialsDB] SET AUTO_UPDATE_STATISTICS_ASYNC OFF 
GO

ALTER DATABASE [TrialsDB] SET DATE_CORRELATION_OPTIMIZATION OFF 
GO

ALTER DATABASE [TrialsDB] SET TRUSTWORTHY OFF 
GO

ALTER DATABASE [TrialsDB] SET ALLOW_SNAPSHOT_ISOLATION OFF 
GO

ALTER DATABASE [TrialsDB] SET PARAMETERIZATION SIMPLE 
GO

ALTER DATABASE [TrialsDB] SET READ_COMMITTED_SNAPSHOT OFF 
GO

ALTER DATABASE [TrialsDB] SET HONOR_BROKER_PRIORITY OFF 
GO

ALTER DATABASE [TrialsDB] SET RECOVERY FULL 
GO

ALTER DATABASE [TrialsDB] SET  MULTI_USER 
GO

ALTER DATABASE [TrialsDB] SET PAGE_VERIFY CHECKSUM  
GO

ALTER DATABASE [TrialsDB] SET DB_CHAINING OFF 
GO

ALTER DATABASE [TrialsDB] SET FILESTREAM( NON_TRANSACTED_ACCESS = OFF ) 
GO

ALTER DATABASE [TrialsDB] SET TARGET_RECOVERY_TIME = 0 SECONDS 
GO

ALTER DATABASE [TrialsDB] SET  READ_WRITE 
GO

Now we will create a table. :)

Create Table in Database

Below is the query to create table in database.

SQL
USE [TrialsDB]
GO

/****** Object:  Table [dbo].[tblTags]    Script Date: 17-Feb-16 10:22:00 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[tblTags](
	[tagId] [int] IDENTITY(1,1) NOT NULL,
	[tagName] [nvarchar](50) NOT NULL,
	[tagDescription] [nvarchar](max) NULL,
 CONSTRAINT [PK_tblTags] PRIMARY KEY CLUSTERED 
(
	[tagId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, _
IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO

Can we insert some data to the table now?

Insert Data to Table

You can use the below query to insert the data:

SQL
USE [TrialsDB]
GO

INSERT INTO [dbo].[tblTags]
           ([tagName]
           ,[tagDescription])
     VALUES
           (<tagName, nvarchar(50),>
           ,<tagDescription, nvarchar(max),>)
GO

So let us say we have inserted the data as follows:

Insertion_In_Table

Insertion_In_Table

The next thing we are going to do is create an 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 processes, you can see the edmx file and other files in your model folder.

ADO_NET_Model_Entity

ADO_NET_Model_Entity

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

C#
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using Load_Tags_From_DB_Using_Angular_JS_In_MVC.Models;

namespace Load_Tags_From_DB_Using_Angular_JS_In_MVC.Controllers
{
    public class TagController : ApiController
    {
        private DBEntities db = new DBEntities();

        // GET api/Tag
        public IEnumerable<tblTag> Get()
        {
            return db.tblTags.AsEnumerable();
        }
    }
}

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

Load_Tags_From_Database_Output

Happy coding!

Conclusion

Did I miss anything that you think is needed? Did you try Web API yet? Have you ever wanted to do this? Could you find this post useful? I hope you liked this article. Please share 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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)