Site icon Sibeesh Passion

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

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 uses Angular JS for our client side operations. You can always get the tips/tricks/blogs about these mentioned technologies from the links given below.

  • AngularJS Tips, Tricks, Blogs
  • MVC Tips, Tricks, Blogs
  • Web API Tips, Tricks, Blogs
  • 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

    Few days back I was trying to use the tagIt widget in one of my application. I could do that with some pre defined tags as a variable. Then I thought why don’t we try some thing 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 can find 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.

  • Angular JS
  • TagIt Plugin
  • jQuery
  • You can 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 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)
    [/html]

    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.

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

    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>
    [/css]

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

    [html]
    <link href="~/Content/jquery-ui.css" rel="stylesheet" />
    <link href="~/Content/jquery.tagit.css" rel="stylesheet" />
    [/html]

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

    Create Angular App

    You can create an Angular module as follows.

    [js]
    var app;
    //Angular App
    app = angular.module(‘tagApp’, []);
    [/js]

    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.

    [js]
    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();
    }
    }
    });
    });
    [/js]

    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.

    [js]
    if ($.inArray(ui.tagLabel, availableTags) < 0) {
    $(‘#error’).show();
    return false;
    } else {
    $(‘#error’).hide();
    }
    [/js]

    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 checks again.

    Tag_It_Control_Defined_Array

    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 Angular JS scripts, don’t worry we will come back here.

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

    [js]
    //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.’);
    });
    }
    });
    [/js]

    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?

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

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

    [js]
    /* 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();
    }
    }
    });
    });
    [/js]

    Now 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
    [/sql]

    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
    [/sql]

    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
    [/sql]

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

    Insertion_In_Table

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

    ADO_NET_Model_Entity

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

    [csharp]
    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();
    }
    }
    }
    [/csharp]

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

    Kindest Regards
    Sibeesh Venu

    Exit mobile version