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.
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?
- @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 uses Angular JS, we will set our ng-app and ng-controller as follows.
- <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.
- <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 style sheets.
- <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.
- var app;
-
- 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)
- {
- $("#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.
- 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_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.
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.
-
- app.controller('tagController', function($scope, tagService)
- {
-
- 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 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?
- //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 these things without AngularJS, meaning we can simply call a jQuery Ajax Get. Do you want to see how? Here it is.
- 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 = 3072 KB, MAXSIZE = UNLIMITED, FILEGROWTH = 1024 KB)
- 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 % )
- 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 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.
- 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.
- 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 following query to insert the data.
- 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.
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.
Then it is time to go back to our Web API controller. Please change the code as below.
- 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();
-
- 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
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: