<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Web API &#8211; Sibeesh Passion</title>
	<atom:link href="https://www.sibeeshpassion.com/category/web-api/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.sibeeshpassion.com</link>
	<description>My passion towards life</description>
	<lastBuildDate>Sun, 15 Aug 2021 14:42:15 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.4</generator>

<image>
	<url>/wp-content/uploads/2017/04/Sibeesh_Passion_Logo_Small.png</url>
	<title>Web API &#8211; Sibeesh Passion</title>
	<link>https://www.sibeeshpassion.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Working With Test Client In Asp Net Web API Help Page</title>
		<link>https://www.sibeeshpassion.com/working-with-test-client-in-asp-net-web-api-help-page/</link>
					<comments>https://www.sibeeshpassion.com/working-with-test-client-in-asp-net-web-api-help-page/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Tue, 31 May 2016 00:00:33 +0000</pubDate>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[Web API]]></category>
		<category><![CDATA[Asp.Net]]></category>
		<category><![CDATA[How to test Web API]]></category>
		<category><![CDATA[Test Web API]]></category>
		<category><![CDATA[Web API Tester]]></category>
		<category><![CDATA[WebApiTestClient]]></category>
		<guid isPermaLink="false">http://sibeecst_passion.com/?p=11654</guid>

					<description><![CDATA[[toc] Introduction In this article we are going to see how we test our API with the help of a package called WebApiTestClient. As you all know, if you create a sample API project you will get a folder HelpPage in Areas. This is for adding the XML description to each controller and actions we use in our API. If you document it well, any one can understand your API, so that you don&#8217;t need to explain what your API will do and what would be the output. If you are new to HelpPage implementation in API, please see here: [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>[toc]</p>
<h2>Introduction</h2>
<p>In this article we are going to see how we test our API with the help of a package called <em>WebApiTestClient</em>. As you all know, if you create a sample API project you will get a folder HelpPage in Areas. This is for adding the XML description to each controller and actions we use in our API. If you document it well, any one can understand your API, so that you don&#8217;t need to explain what your API will do and what would be the output. If you are new to HelpPage implementation in API, please see here: <a href="http://sibeeshpassion.com/working-with-api-help-page-controller-action-description-in-web-api/" target="_blank" rel="noopener">API help page controller action description in Web API</a>. Here I am going to create a <a href="http://sibeeshpassion.com/category/web-api" target="_blank" rel="noopener">Web API</a> with the help page descriptions in <a href="http://sibeeshpassion.com/category/tools/visual-studio/" target="_blank" rel="noopener">Visual Studio</a> 2015. And once after the project is ready I will install the <em>WebApiTestClient </em> package to my solution. I hope you will like this.</p>
<blockquote><p>Please be noted that this package is not officially released by Microsoft. This is a prototype created by <a href="https://social.msdn.microsoft.com/profile/Yao+-+MSFT" target="_blank" rel="noopener">Yao &#8211; MSFT</a></p></blockquote>
<h2><strong>Download the source code</strong></h2>
<p>You can always download the source code here: <a href="https://code.msdn.microsoft.com/Working-With-Test-Client-9fb65ba9" target="_blank" rel="noopener">API Test Client</a></p>
<h2><strong>Background</strong></h2>
<p>For the past few months, I had been working with API projects. Recently I was asked to create an application to test the API I created so that the testing team can test the API easily. Yes I agree that we have tools like Fiddler and Post Man for the same. Still we thought to create our own. As I started my development, I came to know about the package <em>WebApiTestClient</em> which does what we wanted. Finally we decided to stop developing the application and used this wonderful package. Here I am going to show you how can we use this.</p>
<h2><strong>Prerequisites</strong></h2>
<ul>
<li>Visual Studio With Web API Installed</li>
</ul>
<h2><strong>Things we are going to do</strong></h2>
<p>The following are the tasks we are going to do.</p>
<ul>
<li>Setting up database</li>
<li>Creating an Entity Framework</li>
<li>Creating API controller with the Model Created</li>
<li>Installing <em>WebApiTestClient</em></li>
<li>Configuring <em>WebApiTestClient</em></li>
<li>Testing <em>WebApiTestClient</em></li>
</ul>
<h2><strong>Setting up database</strong></h2>
<p>Here I am going to create a database which I created for my demo purposes, you can always create this database by running the queries mentioned here.</p>
<h3><strong>Create database</strong></h3>
<p>[sql]<br />
USE [master]<br />
GO</p>
<p>/****** Object: Database [TrialsDB] Script Date: 5/12/2016 10:56:41 AM ******/<br />
CREATE DATABASE [TrialsDB]<br />
CONTAINMENT = NONE<br />
ON PRIMARY<br />
( NAME = N&#8217;TrialsDB&#8217;, FILENAME = N&#8217;C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\TrialsDB.mdf&#8217; , SIZE = 3072KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )<br />
LOG ON<br />
( NAME = N&#8217;TrialsDB_log&#8217;, FILENAME = N&#8217;C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\TrialsDB_log.ldf&#8217; , SIZE = 1024KB , MAXSIZE = 2048GB , FILEGROWTH = 10%)<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET COMPATIBILITY_LEVEL = 110<br />
GO</p>
<p>IF (1 = FULLTEXTSERVICEPROPERTY(&#8216;IsFullTextInstalled&#8217;))<br />
begin<br />
EXEC [TrialsDB].[dbo].[sp_fulltext_database] @action = &#8216;enable&#8217;<br />
end<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET ANSI_NULL_DEFAULT OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET ANSI_NULLS OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET ANSI_PADDING OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET ANSI_WARNINGS OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET ARITHABORT OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET AUTO_CLOSE OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET AUTO_CREATE_STATISTICS ON<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET AUTO_SHRINK OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET AUTO_UPDATE_STATISTICS ON<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET CURSOR_CLOSE_ON_COMMIT OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET CURSOR_DEFAULT GLOBAL<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET CONCAT_NULL_YIELDS_NULL OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET NUMERIC_ROUNDABORT OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET QUOTED_IDENTIFIER OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET RECURSIVE_TRIGGERS OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET DISABLE_BROKER<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET AUTO_UPDATE_STATISTICS_ASYNC OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET DATE_CORRELATION_OPTIMIZATION OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET TRUSTWORTHY OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET ALLOW_SNAPSHOT_ISOLATION OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET PARAMETERIZATION SIMPLE<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET READ_COMMITTED_SNAPSHOT OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET HONOR_BROKER_PRIORITY OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET RECOVERY FULL<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET MULTI_USER<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET PAGE_VERIFY CHECKSUM<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET DB_CHAINING OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET FILESTREAM( NON_TRANSACTED_ACCESS = OFF )<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET TARGET_RECOVERY_TIME = 0 SECONDS<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET READ_WRITE<br />
GO<br />
[/sql]</p>
<h3><strong>Create table with data</strong></h3>
<p>[sql]<br />
USE [TrialsDB]<br />
GO<br />
/****** Object: Table [dbo].[Product] Script Date: 5/12/2016 10:54:48 AM ******/<br />
SET ANSI_NULLS ON<br />
GO<br />
SET QUOTED_IDENTIFIER ON<br />
GO<br />
CREATE TABLE [dbo].[Product](<br />
[ProductID] [int] NOT NULL,<br />
[Name] [nvarchar](max) NOT NULL,<br />
[ProductNumber] [nvarchar](25) NOT NULL,<br />
[MakeFlag] [bit] NOT NULL,<br />
[FinishedGoodsFlag] [bit] NOT NULL,<br />
[Color] [nvarchar](15) NULL,<br />
[SafetyStockLevel] [smallint] NOT NULL,<br />
[ReorderPoint] [smallint] NOT NULL,<br />
[StandardCost] [money] NOT NULL,<br />
[ListPrice] [money] NOT NULL,<br />
[Size] [nvarchar](5) NULL,<br />
[SizeUnitMeasureCode] [nchar](3) NULL,<br />
[WeightUnitMeasureCode] [nchar](3) NULL,<br />
[Weight] [decimal](8, 2) NULL,<br />
[DaysToManufacture] [int] NOT NULL,<br />
[ProductLine] [nchar](2) NULL,<br />
[Class] [nchar](2) NULL,<br />
[Style] [nchar](2) NULL,<br />
[ProductSubcategoryID] [int] NULL,<br />
[ProductModelID] [int] NULL,<br />
[SellStartDate] [datetime] NOT NULL,<br />
[SellEndDate] [datetime] NULL,<br />
[DiscontinuedDate] [datetime] NULL,<br />
[rowguid] [uniqueidentifier] ROWGUIDCOL NOT NULL,<br />
[ModifiedDate] [datetime] NOT NULL<br />
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]<br />
GO<br />
INSERT [dbo].[Product] ([ProductID], [Name], [ProductNumber], [MakeFlag], [FinishedGoodsFlag], [Color], [SafetyStockLevel], [ReorderPoint], [StandardCost], [ListPrice], [Size], [SizeUnitMeasureCode], [WeightUnitMeasureCode], [Weight], [DaysToManufacture], [ProductLine], [Class], [Style], [ProductSubcategoryID], [ProductModelID], [SellStartDate], [SellEndDate], [DiscontinuedDate], [rowguid], [ModifiedDate]) VALUES (1, N&#8217;Adjustable Race&#8217;, N&#8217;AR-5381&#8242;, 0, 0, NULL, 1000, 750, 0.0000, 0.0000, NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL, NULL, NULL, CAST(0x0000921E00000000 AS DateTime), NULL, NULL, N&#8217;694215b7-08f7-4c0d-acb1-d734ba44c0c8&#8242;, CAST(0x00009A5C00A53CF8 AS DateTime))<br />
INSERT [dbo].[Product] ([ProductID], [Name], [ProductNumber], [MakeFlag], [FinishedGoodsFlag], [Color], [SafetyStockLevel], [ReorderPoint], [StandardCost], [ListPrice], [Size], [SizeUnitMeasureCode], [WeightUnitMeasureCode], [Weight], [DaysToManufacture], [ProductLine], [Class], [Style], [ProductSubcategoryID], [ProductModelID], [SellStartDate], [SellEndDate], [DiscontinuedDate], [rowguid], [ModifiedDate]) VALUES (2, N&#8217;Bearing Ball&#8217;, N&#8217;BA-8327&#8242;, 0, 0, NULL, 1000, 750, 0.0000, 0.0000, NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL, NULL, NULL, CAST(0x0000921E00000000 AS DateTime), NULL, NULL, N&#8217;58ae3c20-4f3a-4749-a7d4-d568806cc537&#8242;, CAST(0x00009A5C00A53CF8 AS DateTime))<br />
INSERT [dbo].[Product] ([ProductID], [Name], [ProductNumber], [MakeFlag], [FinishedGoodsFlag], [Color], [SafetyStockLevel], [ReorderPoint], [StandardCost], [ListPrice], [Size], [SizeUnitMeasureCode], [WeightUnitMeasureCode], [Weight], [DaysToManufacture], [ProductLine], [Class], [Style], [ProductSubcategoryID], [ProductModelID], [SellStartDate], [SellEndDate], [DiscontinuedDate], [rowguid], [ModifiedDate]) VALUES (3, N&#8217;BB Ball Bearing&#8217;, N&#8217;BE-2349&#8242;, 1, 0, NULL, 800, 600, 0.0000, 0.0000, NULL, NULL, NULL, NULL, 1, NULL, NULL, NULL, NULL, NULL, CAST(0x0000921E00000000 AS DateTime), NULL, NULL, N&#8217;9c21aed2-5bfa-4f18-bcb8-f11638dc2e4e&#8217;, CAST(0x00009A5C00A53CF8 AS DateTime))<br />
INSERT [dbo].[Product] ([ProductID], [Name], [ProductNumber], [MakeFlag], [FinishedGoodsFlag], [Color], [SafetyStockLevel], [ReorderPoint], [StandardCost], [ListPrice], [Size], [SizeUnitMeasureCode], [WeightUnitMeasureCode], [Weight], [DaysToManufacture], [ProductLine], [Class], [Style], [ProductSubcategoryID], [ProductModelID], [SellStartDate], [SellEndDate], [DiscontinuedDate], [rowguid], [ModifiedDate]) VALUES (4, N&#8217;Headset Ball Bearings&#8217;, N&#8217;BE-2908&#8242;, 0, 0, NULL, 800, 600, 0.0000, 0.0000, NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL, NULL, NULL, CAST(0x0000921E00000000 AS DateTime), NULL, NULL, N&#8217;ecfed6cb-51ff-49b5-b06c-7d8ac834db8b&#8217;, CAST(0x00009A5C00A53CF8 AS DateTime))<br />
INSERT [dbo].[Product] ([ProductID], [Name], [ProductNumber], [MakeFlag], [FinishedGoodsFlag], [Color], [SafetyStockLevel], [ReorderPoint], [StandardCost], [ListPrice], [Size], [SizeUnitMeasureCode], [WeightUnitMeasureCode], [Weight], [DaysToManufacture], [ProductLine], [Class], [Style], [ProductSubcategoryID], [ProductModelID], [SellStartDate], [SellEndDate], [DiscontinuedDate], [rowguid], [ModifiedDate]) VALUES (316, N&#8217;Blade&#8217;, N&#8217;BL-2036&#8242;, 1, 0, NULL, 800, 600, 0.0000, 0.0000, NULL, NULL, NULL, NULL, 1, NULL, NULL, NULL, NULL, NULL, CAST(0x0000921E00000000 AS DateTime), NULL, NULL, N&#8217;e73e9750-603b-4131-89f5-3dd15ed5ff80&#8242;, CAST(0x00009A5C00A53CF8 AS DateTime))<br />
INSERT [dbo].[Product] ([ProductID], [Name], [ProductNumber], [MakeFlag], [FinishedGoodsFlag], [Color], [SafetyStockLevel], [ReorderPoint], [StandardCost], [ListPrice], [Size], [SizeUnitMeasureCode], [WeightUnitMeasureCode], [Weight], [DaysToManufacture], [ProductLine], [Class], [Style], [ProductSubcategoryID], [ProductModelID], [SellStartDate], [SellEndDate], [DiscontinuedDate], [rowguid], [ModifiedDate]) VALUES (317, N&#8217;LL Crankarm&#8217;, N&#8217;CA-5965&#8242;, 0, 0, N&#8217;Black&#8217;, 500, 375, 0.0000, 0.0000, NULL, NULL, NULL, NULL, 0, NULL, N&#8217;L &#8216;, NULL, NULL, NULL, CAST(0x0000921E00000000 AS DateTime), NULL, NULL, N&#8217;3c9d10b7-a6b2-4774-9963-c19dcee72fea&#8217;, CAST(0x00009A5C00A53CF8 AS DateTime))<br />
INSERT [dbo].[Product] ([ProductID], [Name], [ProductNumber], [MakeFlag], [FinishedGoodsFlag], [Color], [SafetyStockLevel], [ReorderPoint], [StandardCost], [ListPrice], [Size], [SizeUnitMeasureCode], [WeightUnitMeasureCode], [Weight], [DaysToManufacture], [ProductLine], [Class], [Style], [ProductSubcategoryID], [ProductModelID], [SellStartDate], [SellEndDate], [DiscontinuedDate], [rowguid], [ModifiedDate]) VALUES (318, N&#8217;ML Crankarm&#8217;, N&#8217;CA-6738&#8242;, 0, 0, N&#8217;Black&#8217;, 500, 375, 0.0000, 0.0000, NULL, NULL, NULL, NULL, 0, NULL, N&#8217;M &#8216;, NULL, NULL, NULL, CAST(0x0000921E00000000 AS DateTime), NULL, NULL, N&#8217;eabb9a92-fa07-4eab-8955-f0517b4a4ca7&#8217;, CAST(0x00009A5C00A53CF8 AS DateTime))<br />
[/sql]</p>
<h3>Create application</h3>
<p>Our database is ready, now create a Web API application in visual studio and then entity with the above mentioned database.</p>
<div id="attachment_11556" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/05/Creating-Entity-e1463031313825.png"><img fetchpriority="high" decoding="async" aria-describedby="caption-attachment-11556" class="size-large wp-image-11556" src="http://sibeeshpassion.com/wp-content/uploads/2016/05/Creating-Entity-1024x542.png" alt="Creating Entity" width="634" height="336" /></a><p id="caption-attachment-11556" class="wp-caption-text">Creating Entity</p></div>
<p>If you don&#8217;t know how to create an entity in your solution, please read that <a href="http://sibeeshpassion.com/web-api-with-angular-js/" target="_blank" rel="noopener">here</a>. I have mentioned the steps to be followed in that article. Once you have created the entity, you are good to go and create a API controller with the entity created. If you do so, The CRUD actions will be created automatically for you. You may need to edit those actions according to your needs.</p>
<div id="attachment_11557" style="width: 660px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/05/Web-API-2-Controller-with-actions-using-Entity-Framework-e1463031653319.png"><img decoding="async" aria-describedby="caption-attachment-11557" class="size-full wp-image-11557" src="http://sibeeshpassion.com/wp-content/uploads/2016/05/Web-API-2-Controller-with-actions-using-Entity-Framework-e1463031653319.png" alt="Web API 2 Controller with actions, using Entity Framework" width="650" height="457" srcset="/wp-content/uploads/2016/05/Web-API-2-Controller-with-actions-using-Entity-Framework-e1463031653319.png 650w, /wp-content/uploads/2016/05/Web-API-2-Controller-with-actions-using-Entity-Framework-e1463031653319-300x211.png 300w, /wp-content/uploads/2016/05/Web-API-2-Controller-with-actions-using-Entity-Framework-e1463031653319-400x281.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><p id="caption-attachment-11557" class="wp-caption-text">Web API 2 Controller with actions, using Entity Framework</p></div>
<p>Select the Model Class, DBContext then name your controller and click OK. I hope a controller with the CRUD actions. Now we can modify that as follows.</p>
<p>[csharp]<br />
using System;<br />
using System.Collections.Generic;<br />
using System.Data;<br />
using System.Data.Entity;<br />
using System.Data.Entity.Infrastructure;<br />
using System.Linq;<br />
using System.Net;<br />
using System.Net.Http;<br />
using System.Web.Http;<br />
using System.Web.Http.Description;<br />
using ControllerActionDescriptions.Models;</p>
<p>namespace ControllerActionDescriptions.Controllers<br />
{<br />
public class ProductsController : ApiController<br />
{<br />
private TrialsDBEntities db = new TrialsDBEntities();<br />
#region GetProducts<br />
/// &lt;summary&gt;<br />
/// Get all the products available<br />
/// GET: api/Products<br />
/// &lt;/summary&gt;<br />
public IQueryable&lt;Product&gt; GetProducts()<br />
{<br />
return db.Products;<br />
}<br />
#endregion</p>
<p>#region GetProductWithParameter<br />
/// &lt;summary&gt;<br />
/// Get a single product by id<br />
/// GET: api/Products/5<br />
/// &lt;param name=&#8221;id&#8221;&gt;&lt;/param&gt;<br />
/// &lt;/summary&gt;<br />
[ResponseType(typeof(Product))]<br />
public IHttpActionResult GetProduct(int id)<br />
{<br />
Product product = db.Products.Find(id);<br />
if (product == null)<br />
{<br />
return NotFound();<br />
}</p>
<p>return Ok(product);<br />
}<br />
#endregion<br />
// PUT: api/Products/5<br />
[ResponseType(typeof(void))]<br />
public IHttpActionResult PutProduct(int id, Product product)<br />
{<br />
if (!ModelState.IsValid)<br />
{<br />
return BadRequest(ModelState);<br />
}</p>
<p>if (id != product.ProductID)<br />
{<br />
return BadRequest();<br />
}</p>
<p>db.Entry(product).State = EntityState.Modified;</p>
<p>try<br />
{<br />
db.SaveChanges();<br />
}<br />
catch (DbUpdateConcurrencyException)<br />
{<br />
if (!ProductExists(id))<br />
{<br />
return NotFound();<br />
}<br />
else<br />
{<br />
throw;<br />
}<br />
}</p>
<p>return StatusCode(HttpStatusCode.NoContent);<br />
}</p>
<p>// POST: api/Products<br />
[ResponseType(typeof(Product))]<br />
public IHttpActionResult PostProduct(Product product)<br />
{<br />
if (!ModelState.IsValid)<br />
{<br />
return BadRequest(ModelState);<br />
}</p>
<p>db.Products.Add(product);</p>
<p>try<br />
{<br />
db.SaveChanges();<br />
}<br />
catch (DbUpdateException)<br />
{<br />
if (ProductExists(product.ProductID))<br />
{<br />
return Conflict();<br />
}<br />
else<br />
{<br />
throw;<br />
}<br />
}</p>
<p>return CreatedAtRoute(&#8220;DefaultApi&#8221;, new { id = product.ProductID }, product);<br />
}</p>
<p>// DELETE: api/Products/5<br />
[ResponseType(typeof(Product))]<br />
public IHttpActionResult DeleteProduct(int id)<br />
{<br />
Product product = db.Products.Find(id);<br />
if (product == null)<br />
{<br />
return NotFound();<br />
}</p>
<p>db.Products.Remove(product);<br />
db.SaveChanges();</p>
<p>return Ok(product);<br />
}</p>
<p>protected override void Dispose(bool disposing)<br />
{<br />
if (disposing)<br />
{<br />
db.Dispose();<br />
}<br />
base.Dispose(disposing);<br />
}</p>
<p>private bool ProductExists(int id)<br />
{<br />
return db.Products.Count(e =&gt; e.ProductID == id) &gt; 0;<br />
}<br />
}<br />
}<br />
[/csharp]</p>
<h2><strong>Installing WebApiTestClient</strong></h2>
<p>To install the package, please go to your Package Manage Console from NuGet Package Manager and run the following command.</p>
<p>[csharp]<br />
Install-Package WebApiTestClient<br />
[/csharp]</p>
<p>You can always get the details about the package <a href="https://www.nuget.org/packages/WebApiTestClient" target="_blank" rel="noopener">here</a>.</p>
<p>Once you install the package, you can see some files are added to your Script and Area folder as preceding.</p>
<div id="attachment_11655" style="width: 291px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/05/Script-and-Area-Folder.png"><img decoding="async" aria-describedby="caption-attachment-11655" class="size-full wp-image-11655" src="http://sibeeshpassion.com/wp-content/uploads/2016/05/Script-and-Area-Folder.png" alt="Script and Area Folder" width="281" height="780" srcset="/wp-content/uploads/2016/05/Script-and-Area-Folder.png 281w, /wp-content/uploads/2016/05/Script-and-Area-Folder-108x300.png 108w, /wp-content/uploads/2016/05/Script-and-Area-Folder-216x600.png 216w" sizes="(max-width: 281px) 100vw, 281px" /></a><p id="caption-attachment-11655" class="wp-caption-text">Script and Area Folder</p></div>
<h2><strong>Configuring WebApiTestClient</strong></h2>
<p>To configure the WebApiTestClient, please go to the folder Areas-&gt;Views-&gt;Help and then click on Api.cshtml</p>
<div id="attachment_11656" style="width: 272px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/05/Api-Cshtml.png"><img decoding="async" aria-describedby="caption-attachment-11656" class="size-full wp-image-11656" src="http://sibeeshpassion.com/wp-content/uploads/2016/05/Api-Cshtml.png" alt="Api Cshtml" width="262" height="232" /></a><p id="caption-attachment-11656" class="wp-caption-text">Api Cshtml</p></div>
<p>This is the view shown when you click on each API in your help page. Now add the preceding code block to that view.</p>
<p>[html]<br />
@Html.DisplayForModel(&#8220;TestClientDialogs&#8221;)<br />
@section Scripts<br />
{<br />
&lt;link href=&#8221;~/Areas/HelpPage/HelpPage.css&#8221; rel=&#8221;stylesheet&#8221; type=&#8221;text/css&#8221; /&gt;<br />
@Html.DisplayForModel(&#8220;TestClientReferences&#8221;)<br />
}<br />
[/html]</p>
<div id="attachment_11657" style="width: 660px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/05/Code-Block-e1464327127249.png"><img decoding="async" aria-describedby="caption-attachment-11657" class="size-full wp-image-11657" src="http://sibeeshpassion.com/wp-content/uploads/2016/05/Code-Block-e1464327127249.png" alt="Code Block" width="650" height="503" srcset="/wp-content/uploads/2016/05/Code-Block-e1464327127249.png 461w, /wp-content/uploads/2016/05/Code-Block-e1464327127249-300x232.png 300w, /wp-content/uploads/2016/05/Code-Block-e1464327127249-400x310.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><p id="caption-attachment-11657" class="wp-caption-text">Code Block</p></div>
<h2><strong>Testing WebApiTestClient</strong></h2>
<p>Now run your API application and go to the help page for any controller action, you can see a button called Test API on the bottom. If you click on that you will get a pop where you can test your API action.</p>
<div id="attachment_11658" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/05/Test-API-Client-Output-e1464327451839.png"><img decoding="async" aria-describedby="caption-attachment-11658" class="size-large wp-image-11658" src="http://sibeeshpassion.com/wp-content/uploads/2016/05/Test-API-Client-Output-1024x451.png" alt="Test API Client Output" width="634" height="279" /></a><p id="caption-attachment-11658" class="wp-caption-text">Test API Client Output</p></div>
<p>Now if you send your request by clicking the send button, you will get an output as follows.</p>
<div id="attachment_11659" style="width: 660px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/05/Test-API-Client-Output-With-Response-e1464327640682.png"><img decoding="async" aria-describedby="caption-attachment-11659" class="size-full wp-image-11659" src="http://sibeeshpassion.com/wp-content/uploads/2016/05/Test-API-Client-Output-With-Response-e1464327640682.png" alt="Test API Client Output With Response" width="650" height="484" srcset="/wp-content/uploads/2016/05/Test-API-Client-Output-With-Response-e1464327640682.png 479w, /wp-content/uploads/2016/05/Test-API-Client-Output-With-Response-e1464327640682-300x223.png 300w, /wp-content/uploads/2016/05/Test-API-Client-Output-With-Response-e1464327640682-400x298.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><p id="caption-attachment-11659" class="wp-caption-text">Test API Client Output With Response</p></div>
<p>You can always give id parameter as follows.</p>
<div id="attachment_11660" style="width: 660px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/05/Test-Client-With-Parameters-e1464327873548.png"><img decoding="async" aria-describedby="caption-attachment-11660" class="size-full wp-image-11660" src="http://sibeeshpassion.com/wp-content/uploads/2016/05/Test-Client-With-Parameters-e1464327873548.png" alt="Test Client With Parameters" width="650" height="302" srcset="/wp-content/uploads/2016/05/Test-Client-With-Parameters-e1464327873548.png 650w, /wp-content/uploads/2016/05/Test-Client-With-Parameters-e1464327873548-300x139.png 300w, /wp-content/uploads/2016/05/Test-Client-With-Parameters-e1464327873548-400x186.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><p id="caption-attachment-11660" class="wp-caption-text">Test Client With Parameters</p></div>
<p>You can also give content-length and content-type in your post request as follows.</p>
<div id="attachment_11661" style="width: 660px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/05/Test-Client-With-Post-e1464328070355.png"><img decoding="async" aria-describedby="caption-attachment-11661" class="size-full wp-image-11661" src="http://sibeeshpassion.com/wp-content/uploads/2016/05/Test-Client-With-Post-e1464328070355.png" alt="Test Client With Post" width="650" height="468" srcset="/wp-content/uploads/2016/05/Test-Client-With-Post-e1464328070355.png 496w, /wp-content/uploads/2016/05/Test-Client-With-Post-e1464328070355-300x216.png 300w, /wp-content/uploads/2016/05/Test-Client-With-Post-e1464328070355-400x288.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><p id="caption-attachment-11661" class="wp-caption-text">Test Client With Post</p></div>
<div id="attachment_11662" style="width: 660px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/05/Test-Client-With-PUT-Request-e1464328191663.png"><img decoding="async" aria-describedby="caption-attachment-11662" class="size-full wp-image-11662" src="http://sibeeshpassion.com/wp-content/uploads/2016/05/Test-Client-With-PUT-Request-e1464328191663.png" alt="Test Client With PUT Request" width="650" height="542" srcset="/wp-content/uploads/2016/05/Test-Client-With-PUT-Request-e1464328191663.png 428w, /wp-content/uploads/2016/05/Test-Client-With-PUT-Request-e1464328191663-300x250.png 300w, /wp-content/uploads/2016/05/Test-Client-With-PUT-Request-e1464328191663-400x334.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><p id="caption-attachment-11662" class="wp-caption-text">Test Client With PUT Request</p></div>
<h2><strong>References</strong></h2>
<ul>
<li><a href="https://blogs.msdn.microsoft.com/yaohuang1/2012/12/02/adding-a-simple-test-client-to-asp-net-web-api-help-page/" target="_blank" rel="noopener">Sample Test Client</a></li>
<li><a href="https://www.nuget.org/packages/WebApiTestClient" target="_blank" rel="noopener">WebApiTestClient</a></li>
</ul>
<p>Author has already posted the source code in GitHub, please check <a href="https://github.com/yaohuang/WebApiTestClient" target="_blank" rel="noopener">here</a>.</p>
<p>Have a happy coding!.</p>
<h2><strong>Conclusion</strong></h2>
<p>Did I miss anything that you may think which is needed? Could you find this post as useful? I hope you liked this article. Please share me your valuable suggestions and feedback.</p>
<h2><strong>Your turn. What do you think?</strong></h2>
<p>A blog isn&#8217;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.</p>
<p>Kindest Regards<br />
Sibeesh Venu</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.sibeeshpassion.com/working-with-test-client-in-asp-net-web-api-help-page/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Web API With HttpClient Or Consume Web API From Console Application</title>
		<link>https://www.sibeeshpassion.com/web-api-with-httpclient-or-consume-web-api-from-console-application/</link>
					<comments>https://www.sibeeshpassion.com/web-api-with-httpclient-or-consume-web-api-from-console-application/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Mon, 28 Mar 2016 00:00:37 +0000</pubDate>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[Web API]]></category>
		<category><![CDATA[AspNet]]></category>
		<category><![CDATA[HttpClient]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[Web API And HttpClient]]></category>
		<category><![CDATA[Web API In Console Application]]></category>
		<guid isPermaLink="false">http://sibeecst_passion.com/?p=11424</guid>

					<description><![CDATA[In this article, we are going to learn how we can call Web API using HttpClient. Normally we call a Web API either from a jQuery Ajax or from Angular JS right? Recently I came across a need of calling our Web API from the server-side itself. Here I am going to use two Visual Studio applications. One is our normal Web API application in which I have a Web API controller and actions, another one is a console application where I consume my Web API. Sounds good? I am using Visual Studio 2015. You can always get the tips/tricks/blogs [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p>In this article, we are going to learn how we can call Web API using HttpClient. Normally we call a Web API either from a jQuery Ajax or from Angular JS right? Recently I came across a need of calling our Web API from the server-side itself. Here I am going to use two Visual Studio applications. One is our normal Web API application in which I have a Web API controller and actions, another one is a console application where I consume my Web API. Sounds good? I am using Visual Studio 2015. You can always get the tips/tricks/blogs about these mentioned technologies from the links given below.</p>



<ul class="wp-block-list"><li><a href="http://sibeeshpassion.com/category/mvc/" target="_blank" rel="noopener">MVC Tips, Tricks, Blogs</a></li><li><a href="http://sibeeshpassion.com/category/web-api/" target="_blank" rel="noopener">Web API Tips, Tricks, Blogs</a></li></ul>



<p>Now we will go and create our application. I hope you will like this.</p>



<p><strong>Download the source code</strong></p>



<p>You can always download the source code here.</p>



<ul class="wp-block-list"><li><a href="https://github.com/SibeeshVenu/WebAPI-HttpClient" target="_blank" rel="noreferrer noopener">Web API Application and Consumer</a></li></ul>



<p><strong>Background</strong></p>



<p>We all use Web API in our applications to implement HTTP services. HTTP services are much simpler than ever if we use Web API. But the fact is, the benefits of a Web API is not limited to that. Previously we use WCF services instead of Web API, where we were working with endpoints and all. Here I am going to explain an important feature of a Web API that we can call Web API from our server itself instead of using an Ajax Call. That is pretty cool, right? Now we will create our application.</p>



<p>First, we will create our Web API application.</p>



<p><strong>Creating Web API application</strong></p>



<p>Click File-&gt; New-&gt; Project then select MVC application. We will select the template as empty from the following pop-up and select the core references and folders for MVC.</p>



<figure class="wp-block-image alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/Empty-Template-With-MVC-And-Web-API-Folders-e1458711950206.png"><img decoding="async" width="650" height="484" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/Empty-Template-With-MVC-And-Web-API-Folders-e1458711950206.png" alt="Empty Template With MVC And Web API Folders" class="wp-image-11405" srcset="/wp-content/uploads/2016/03/Empty-Template-With-MVC-And-Web-API-Folders-e1458711950206.png 650w, /wp-content/uploads/2016/03/Empty-Template-With-MVC-And-Web-API-Folders-e1458711950206-300x223.png 300w, /wp-content/uploads/2016/03/Empty-Template-With-MVC-And-Web-API-Folders-e1458711950206-400x298.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><figcaption>Empty Template With MVC And Web API Folders</figcaption></figure>



<p>Once you click OK, a project with MVC like folder structure with core references will be created for you.</p>



<figure class="wp-block-image alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/Folder-Structure-And-References-For-Empty-MVC-Project.png"><img decoding="async" width="267" height="367" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/Folder-Structure-And-References-For-Empty-MVC-Project.png" alt="Folder Structure And References For Empty MVC Project" class="wp-image-11362" srcset="/wp-content/uploads/2016/03/Folder-Structure-And-References-For-Empty-MVC-Project.png 267w, /wp-content/uploads/2016/03/Folder-Structure-And-References-For-Empty-MVC-Project-218x300.png 218w" sizes="(max-width: 267px) 100vw, 267px" /></a><figcaption>Folder Structure And References For Empty MVC Project</figcaption></figure>



<p><strong>Using the code</strong></p>



<p>We will set up our database first so that we can create an Entity Model for our application later.</p>



<p><strong>Create a database</strong></p>



<p>The following query can be used to create a database in your SQL Server.</p>



<script src="https://gist.github.com/SibeeshVenu/5c2eef73bb0c3a856cb538333543d0c6.js"></script>



<p>Now we will create the table we needed. As of now, I am going to create the table <em>tblTags </em></p>



<p><strong>Create tables in the database</strong></p>



<p>Below is the query to create the table <em>tblTags</em>.</p>



<script src="https://gist.github.com/SibeeshVenu/2673dc6b515dde9485790d7fb180dc69.js"></script>



<p>Can we insert some data into the tables now?</p>



<p><strong>Insert data to the table</strong></p>



<p>You can use the below query to insert the data to the table <em>tblTags</em></p>



<script src="https://gist.github.com/SibeeshVenu/6bfd40c9b96b415d07db6269593a6050.js"></script>



<p>The next thing we are going to do is creating an ADO.NET Entity Data Model.</p>



<p><strong>Create Entity Data Model</strong></p>



<p>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. Here I gave Dashboard for our Entity data model name. Now you can see a file with an edmx extension has been created.<br>Now will create our Web API controller.</p>



<p><strong>Create Web API Controller</strong></p>



<p>To create a Web API controller, just right click on your controller folder and click Add -&gt; Controller -&gt; Select Web API 2 controller with actions, using Entity Framework.</p>



<figure class="wp-block-image alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/Web-API-2-Controller-With-Actions-Using-Entity-Framework-e1458709497551.png"><img decoding="async" width="650" height="448" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/Web-API-2-Controller-With-Actions-Using-Entity-Framework-e1458709497551.png" alt="Web API 2 Controller With Actions Using Entity Framework" class="wp-image-11401" srcset="/wp-content/uploads/2016/03/Web-API-2-Controller-With-Actions-Using-Entity-Framework-e1458709497551.png 650w, /wp-content/uploads/2016/03/Web-API-2-Controller-With-Actions-Using-Entity-Framework-e1458709497551-300x207.png 300w, /wp-content/uploads/2016/03/Web-API-2-Controller-With-Actions-Using-Entity-Framework-e1458709497551-160x110.png 160w, /wp-content/uploads/2016/03/Web-API-2-Controller-With-Actions-Using-Entity-Framework-e1458709497551-400x276.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><figcaption>Web API 2 Controller With Actions Using Entity Framework</figcaption></figure>



<p>Now select <em>tblTag (WebAPIWithHttpClient.Models)</em> as our Model class and <em>TrialsDBEntities (WebAPIWithHttpClient.Models)</em> as data context class. This time we will select controller with async actions.</p>



<figure class="wp-block-image alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/Web-API-Controller-With-Async-Actions.png"><img decoding="async" width="593" height="233" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/Web-API-Controller-With-Async-Actions.png" alt="Web API Controller With Async Actions" class="wp-image-11425" srcset="/wp-content/uploads/2016/03/Web-API-Controller-With-Async-Actions.png 593w, /wp-content/uploads/2016/03/Web-API-Controller-With-Async-Actions-300x118.png 300w, /wp-content/uploads/2016/03/Web-API-Controller-With-Async-Actions-400x157.png 400w" sizes="(max-width: 593px) 100vw, 593px" /></a><figcaption>Web API Controller With Async Actions</figcaption></figure>



<p>As you can see It has been given the name of our controller as <em>tblTags</em>. Here I am not going to change that, if you wish to change, you can do that.</p>



<p>Now you will be given the following codes in our new Web API controller.</p>



<script src="https://gist.github.com/SibeeshVenu/d47bd69da2de534bd9f53224e464bb76.js"></script>



<p>As you can see, we have actions for,</p>



<ul class="wp-block-list"><li>Get</li><li>Post</li><li>Put</li><li>Delete</li></ul>



<p>So the coding part to fetch the data from the database is ready, now we need to check whether our Web API is ready for action!. To check that, you just need to run the URL <em>http://localhost:7967/api/tbltags</em>. Here <em>tblTags</em> is our Web API controller name. I hope you get the data as a result.</p>



<figure class="wp-block-image alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/Web_API_Result-e1458733092316.png"><img decoding="async" width="650" height="342" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/Web_API_Result-e1458733092316.png" alt="Web_API_Result" class="wp-image-11413" srcset="/wp-content/uploads/2016/03/Web_API_Result-e1458733092316.png 650w, /wp-content/uploads/2016/03/Web_API_Result-e1458733092316-300x158.png 300w, /wp-content/uploads/2016/03/Web_API_Result-e1458733092316-600x315.png 600w, /wp-content/uploads/2016/03/Web_API_Result-e1458733092316-400x210.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><figcaption>Web_API_Result</figcaption></figure>



<p>As of now, our Web API application is ready, and we have just tested whether it is working or not. Now we can move on to create a console application where we can consume this Web API with the help of HttpClient. So shall we do that?</p>



<p><strong>Create Console Application To Consume Web API</strong></p>



<p>To create a console application, Click File -&gt; New -&gt; Click Windows -&gt; Select Console application -&gt; Name your application -&gt; OK</p>



<figure class="wp-block-image alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/Console-Application-e1458836504170.png"><img decoding="async" width="650" height="396" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/Console-Application-e1458836504170.png" alt="Console Application" class="wp-image-11426" srcset="/wp-content/uploads/2016/03/Console-Application-e1458836504170.png 650w, /wp-content/uploads/2016/03/Console-Application-e1458836504170-300x183.png 300w, /wp-content/uploads/2016/03/Console-Application-e1458836504170-400x244.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><figcaption>Console Application</figcaption></figure>



<p>I hope now you have a class called Program. cs with the below codes.</p>



<script src="https://gist.github.com/SibeeshVenu/bbbe25768fa7a0f6ee294a2e7ef794a3.js"></script>



<p>Now we will start our coding, We will create a class called <em>tblTag </em>with some properties so that we can use those when we need them.</p>



<script src="https://gist.github.com/SibeeshVenu/ad2e7b0da0ad725a19777b76a2f55d5c.js"></script>



<p>To get started using the class <em>HttpClient</em>, you must import the namespace as follows.</p>



<pre class="wp-block-code"><code>using System.Net.Http;</code></pre>



<p>Once you have imported the namespaces, we will set our HttpClient and the properties as follows.</p>



<script src="https://gist.github.com/SibeeshVenu/fe0d1863a944dddb528ecff8d376cf76.js"></script>



<p>As you can see we are just giving the base address of our API and setting the response header. Now we will create an async action to get the data from our database by calling our Web API.</p>



<p><strong>Get operation using HttpClient</strong></p>



<pre class="wp-block-code"><code>MyAPIGet(cons).Wait();</code></pre>



<p>Following is the definition of the <em>MyAPIGet </em>function.</p>



<script src="https://gist.github.com/SibeeshVenu/79b3004ee97c61d112100e8324a0e7fb.js"></script>



<p>Here <em>res.EnsureSuccessStatusCode();</em> ensure that it throws errors if we get any. If you don&#8217;t need to throw the errors, please remove this line of code. If the async call is a success, the value in <em>IsSuccessStatusCode</em> will be true.</p>



<p>Now when you run the above code, there are chances to get an error as follows.</p>



<p><em>Error CS1061 &#8216;HttpContent&#8217; does not contain a definition for &#8216;ReadAsAsync&#8217; and no extension method &#8216;ReadAsAsync&#8217; accepting a first argument of type &#8216;HttpContent&#8217; could be found (are you missing a using directive or an assembly reference?)</em></p>



<p>This is just because the <em>ReadAsAsync</em> is a part of <em>System.Net.Http.Formatting.dll</em> which we have not added to our application as a reference yet. Now we will do that? Sounds OK?</p>



<p>Just right click on the references and click add reference -&gt; Click browse -&gt; search for <em>System.Net.Http.Formatting.dll</em> &#8211; Click OK</p>



<figure class="wp-block-image alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/Add-References-e1458838521697.png"><img decoding="async" width="650" height="447" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/Add-References-e1458838521697.png" alt="Add References" class="wp-image-11427" srcset="/wp-content/uploads/2016/03/Add-References-e1458838521697.png 650w, /wp-content/uploads/2016/03/Add-References-e1458838521697-300x206.png 300w, /wp-content/uploads/2016/03/Add-References-e1458838521697-160x110.png 160w, /wp-content/uploads/2016/03/Add-References-e1458838521697-400x275.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><figcaption>Add References</figcaption></figure>



<p>Please add <em>Newtonsoft.Json</em> also. Now let us run our project and see our output.</p>



<figure class="wp-block-image alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/Web_API_Consumer_Get_Output1-e1458882223957.png"><img decoding="async" width="650" height="328" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/Web_API_Consumer_Get_Output1-e1458882223957.png" alt="Web_API_Consumer_Get_Output" class="wp-image-11429" srcset="/wp-content/uploads/2016/03/Web_API_Consumer_Get_Output1-e1458882223957.png 650w, /wp-content/uploads/2016/03/Web_API_Consumer_Get_Output1-e1458882223957-300x151.png 300w, /wp-content/uploads/2016/03/Web_API_Consumer_Get_Output1-e1458882223957-400x202.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><figcaption>Web_API_Consumer_Get_Output</figcaption></figure>



<p>Now shall we create a function for updating the record? Yes, we are going to create a function with the &#8216;Put&#8217; request. Please copy and paste the preceding code for that.</p>



<p><strong>Put operation using HttpClient</strong></p>



<script src="https://gist.github.com/SibeeshVenu/bdbfdf46d94b59f919feb5e55dd5b75b.js"></script>



<p>As you can see, we are updating the record as below once we get the response from <em>await cons.GetAsync(&#8220;api/tblTags/2&#8221;)</em> .</p>



<script src="https://gist.github.com/SibeeshVenu/93b430884a048b02120aab726593212a.js"></script>



<p>Again, run your application and check whether the tag name has been changed to &#8216;New Tag&#8217;.</p>



<figure class="wp-block-image alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/Web_API_Consumer_Put_Output-e1458882875423.png"><img decoding="async" width="650" height="328" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/Web_API_Consumer_Put_Output-e1458882875423.png" alt="Web_API_Consumer_Put_Output" class="wp-image-11430" srcset="/wp-content/uploads/2016/03/Web_API_Consumer_Put_Output-e1458882875423.png 650w, /wp-content/uploads/2016/03/Web_API_Consumer_Put_Output-e1458882875423-300x151.png 300w, /wp-content/uploads/2016/03/Web_API_Consumer_Put_Output-e1458882875423-400x202.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><figcaption>Web_API_Consumer_Put_Output</figcaption></figure>



<p>Now did you see that your tag name has been changed? If yes, we are ready to go for our next operation. Are you ready?</p>



<p><strong>Delete operation using HttpClient</strong></p>



<p>We will follow the same procedure for delete operation too. Please see the code for the delete operation below.</p>



<script src="https://gist.github.com/SibeeshVenu/84ff6853fec53f7b93345170be8050bd.js"></script>



<p>To delete a record we uses <em> res = await cons.DeleteAsync(&#8220;api/tblTags/2&#8221;);</em> method. Now run your application and see the result.</p>



<figure class="wp-block-image alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/Web_API_Consumer_Delete_Output-e1458883191973.png"><img decoding="async" width="650" height="328" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/Web_API_Consumer_Delete_Output-e1458883191973.png" alt="Web_API_Consumer_Delete_Output" class="wp-image-11431" srcset="/wp-content/uploads/2016/03/Web_API_Consumer_Delete_Output-e1458883191973.png 650w, /wp-content/uploads/2016/03/Web_API_Consumer_Delete_Output-e1458883191973-300x151.png 300w, /wp-content/uploads/2016/03/Web_API_Consumer_Delete_Output-e1458883191973-400x202.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><figcaption>Web_API_Consumer_Delete_Output</figcaption></figure>



<p>What action is pending now? Yes, it is Post.</p>



<p><strong>Post-operation using HttpClient</strong></p>



<p>Please add the below function to your project for the post-operation.</p>



<script src="https://gist.github.com/SibeeshVenu/b52bb82946ad305c5fa95bc1ccbe6ae8.js"></script>



<p>We are just creating a new tblTag and assign some values, once the object is ready we are calling the method PostAsJsonAsync as follows.</p>



<script src="https://gist.github.com/SibeeshVenu/4f73e7e9ee9355afb808e0bbbe00647c.js"></script>



<p>As you have noticed, I have not provided the <em>tagId</em> in the object, do you know why? I have already set Identity Specification with Identity Increment 1 in my table tblTags in the SQL database.</p>



<p>Now we will see the output. Shall we?</p>



<figure class="wp-block-image alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/Web_API_Consumer_Post_Output-e1458883741126.png"><img decoding="async" width="650" height="328" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/Web_API_Consumer_Post_Output-e1458883741126.png" alt="Web_API_Consumer_Post_Output" class="wp-image-11432" srcset="/wp-content/uploads/2016/03/Web_API_Consumer_Post_Output-e1458883741126.png 650w, /wp-content/uploads/2016/03/Web_API_Consumer_Post_Output-e1458883741126-300x151.png 300w, /wp-content/uploads/2016/03/Web_API_Consumer_Post_Output-e1458883741126-400x202.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><figcaption>Web_API_Consumer_Post_Output</figcaption></figure>



<p>We have done everything!. That&#8217;s fantastic right? Have a happy coding.</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow"><p>You can always use WebClient also for this requirement, that I will share in an another article.</p></blockquote>



<p><strong>Conclusion</strong></p>



<p>Did I miss anything that you may think is needed? Did you try Web API yet? Have you ever wanted to call a Web API from the server itself or any console application? Could you find this post useful? I hope you liked this article. Please share me your valuable suggestions and feedback.</p>



<p><strong>Your turn. What do you think?</strong></p>



<p>A blog isn&#8217;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.</p>



<p>Kindest Regards<br>Sibeesh Venu</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.sibeeshpassion.com/web-api-with-httpclient-or-consume-web-api-from-console-application/feed/</wfw:commentRss>
			<slash:comments>8</slash:comments>
		
		
			</item>
		<item>
		<title>Caching In Web API</title>
		<link>https://www.sibeeshpassion.com/caching-in-web-api/</link>
					<comments>https://www.sibeeshpassion.com/caching-in-web-api/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Thu, 24 Mar 2016 00:00:39 +0000</pubDate>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[Web API]]></category>
		<category><![CDATA[Asp.Net]]></category>
		<category><![CDATA[Caching]]></category>
		<category><![CDATA[Caching In Web API]]></category>
		<category><![CDATA[MemoryCache]]></category>
		<category><![CDATA[MVC]]></category>
		<guid isPermaLink="false">http://sibeecst_passion.com/?p=11410</guid>

					<description><![CDATA[In this article we will are going to learn how we can use caching in Web API. Normally caching is the process of storing data somewhere for the future requests, in our case we can avoid the unwanted hit to database to get the data if we cache the data somewhere, this way we can make sure that the data is served in a faster manner. Here we are going to see the caching in our Web API controller. If you are new to caching, I have written an article about caching in MVC, please read it here: Caching In [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>In this article we will are going to learn how we can use caching in Web API. Normally caching is the process of storing data somewhere for the future requests, in our case we can avoid the unwanted hit to database to get the data if we cache the data somewhere, this way we can make sure that the data is served in a faster manner. Here we are going to see the caching in our Web API controller. If you are new to caching, I have written an article about caching in MVC, please read it here: <a href="http://sibeeshpassion.com/caching-in-mvc/" target="_blank" rel="noopener">Caching In MVC</a>. We will explain caching with the help of <em>System.Runtime.Caching</em> which is given by Microsoft. This DLL is not available in the default references, you may need to add that separately. I will show you how. I am creating this application in Visual Studio 2015. You can always get the tips/tricks/blogs about these mentioned technologies from the links given below. </p>
<li><a href="http://sibeeshpassion.com/category/mvc/" target="_blank" rel="noopener">MVC Tips, Tricks, Blogs</a></li>
<li><a href="http://sibeeshpassion.com/category/web-api/" target="_blank" rel="noopener">Web API Tips, Tricks, Blogs</a></li>
<p>Now we will go and create our application. I hope you will like this. </p>
<p><strong>Download the source code</strong></p>
<p>You can always download the source code here.</p>
<li><a href="https://code.msdn.microsoft.com/Caching-In-Web-API-cb40be30" target="_blank" rel="noopener">Caching In Web API</a></li>
<p><strong>Background</strong></p>
<p>For the past few days I am working with Web API.Here we are going to see a demo of how to use Caching in Web API in our MVC application. We are going to use the DLL <em>System.Runtime.Caching.dll</em>, which you need to add as reference. </p>
<p><strong>Create a MVC application</strong></p>
<p>Click File-> New-> Project then select MVC application. From the following pop up we will select the template as empty and select the core references and folders for MVC. </p>
<p><div id="attachment_11405" style="width: 660px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/Empty-Template-With-MVC-And-Web-API-Folders-e1458711950206.png"><img decoding="async" aria-describedby="caption-attachment-11405" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/Empty-Template-With-MVC-And-Web-API-Folders-e1458711950206.png" alt="Empty Template With MVC And Web API Folders" width="650" height="484" class="size-full wp-image-11405" srcset="/wp-content/uploads/2016/03/Empty-Template-With-MVC-And-Web-API-Folders-e1458711950206.png 650w, /wp-content/uploads/2016/03/Empty-Template-With-MVC-And-Web-API-Folders-e1458711950206-300x223.png 300w, /wp-content/uploads/2016/03/Empty-Template-With-MVC-And-Web-API-Folders-e1458711950206-400x298.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><p id="caption-attachment-11405" class="wp-caption-text">Empty Template With MVC And Web API Folders</p></div></p>
<p>Once you click OK, a project with MVC like folder structure with core references will be created for you.</p>
<p><div id="attachment_11362" style="width: 277px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/Folder-Structure-And-References-For-Empty-MVC-Project.png"><img decoding="async" aria-describedby="caption-attachment-11362" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/Folder-Structure-And-References-For-Empty-MVC-Project.png" alt="Folder Structure And References For Empty MVC Project" width="267" height="367" class="size-full wp-image-11362" srcset="/wp-content/uploads/2016/03/Folder-Structure-And-References-For-Empty-MVC-Project.png 267w, /wp-content/uploads/2016/03/Folder-Structure-And-References-For-Empty-MVC-Project-218x300.png 218w" sizes="(max-width: 267px) 100vw, 267px" /></a><p id="caption-attachment-11362" class="wp-caption-text">Folder Structure And References For Empty MVC Project</p></div></p>
<p>Once your application is ready, we can add the reference for <em>System.Runtime.Caching</em></p>
<p><strong>Add reference for System.Runtime.Caching</strong></p>
<p>To add the reference, right click on References and click Add reference.</p>
<p><div id="attachment_11411" style="width: 492px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/Add_References_.png"><img decoding="async" aria-describedby="caption-attachment-11411" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/Add_References_.png" alt="Add_References" width="482" height="316" class="size-full wp-image-11411" srcset="/wp-content/uploads/2016/03/Add_References_.png 482w, /wp-content/uploads/2016/03/Add_References_-300x197.png 300w, /wp-content/uploads/2016/03/Add_References_-400x262.png 400w" sizes="(max-width: 482px) 100vw, 482px" /></a><p id="caption-attachment-11411" class="wp-caption-text">Add_References</p></div></p>
<p>Now click on the browse button, and search for <em>System.Runtime.Caching</em></p>
<p><div id="attachment_11412" style="width: 660px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/References_Found_-e1458732611680.png"><img decoding="async" aria-describedby="caption-attachment-11412" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/References_Found_-e1458732611680.png" alt="References_Found_" width="650" height="373" class="size-full wp-image-11412" srcset="/wp-content/uploads/2016/03/References_Found_-e1458732611680.png 650w, /wp-content/uploads/2016/03/References_Found_-e1458732611680-300x172.png 300w, /wp-content/uploads/2016/03/References_Found_-e1458732611680-400x230.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><p id="caption-attachment-11412" class="wp-caption-text">References_Found_</p></div></p>
<p>And the click OK, the DLL will be added to your references now. </p>
<p><strong>Using the code</strong></p>
<p>We will set up our database first so that we can create Entity Model for our application later. </p>
<p><strong>Create a database</strong></p>
<p>The following query can be used to create a database in your SQL Server.</p>
<p>[sql]<br />
USE [master]<br />
GO</p>
<p>/****** Object:  Database [TrialsDB]<br />
CREATE DATABASE [TrialsDB]<br />
 CONTAINMENT = NONE<br />
 ON  PRIMARY<br />
( NAME = N&#8217;TrialsDB&#8217;, FILENAME = N&#8217;C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\TrialsDB.mdf&#8217; , SIZE = 3072KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )<br />
 LOG ON<br />
( NAME = N&#8217;TrialsDB_log&#8217;, FILENAME = N&#8217;C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\TrialsDB_log.ldf&#8217; , SIZE = 1024KB , MAXSIZE = 2048GB , FILEGROWTH = 10%)<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET COMPATIBILITY_LEVEL = 110<br />
GO</p>
<p>IF (1 = FULLTEXTSERVICEPROPERTY(&#8216;IsFullTextInstalled&#8217;))<br />
begin<br />
EXEC [TrialsDB].[dbo].[sp_fulltext_database] @action = &#8216;enable&#8217;<br />
end<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET ANSI_NULL_DEFAULT OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET ANSI_NULLS OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET ANSI_PADDING OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET ANSI_WARNINGS OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET ARITHABORT OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET AUTO_CLOSE OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET AUTO_CREATE_STATISTICS ON<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET AUTO_SHRINK OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET AUTO_UPDATE_STATISTICS ON<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET CURSOR_CLOSE_ON_COMMIT OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET CURSOR_DEFAULT  GLOBAL<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET CONCAT_NULL_YIELDS_NULL OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET NUMERIC_ROUNDABORT OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET QUOTED_IDENTIFIER OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET RECURSIVE_TRIGGERS OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET  DISABLE_BROKER<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET AUTO_UPDATE_STATISTICS_ASYNC OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET DATE_CORRELATION_OPTIMIZATION OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET TRUSTWORTHY OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET ALLOW_SNAPSHOT_ISOLATION OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET PARAMETERIZATION SIMPLE<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET READ_COMMITTED_SNAPSHOT OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET HONOR_BROKER_PRIORITY OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET RECOVERY FULL<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET  MULTI_USER<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET PAGE_VERIFY CHECKSUM<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET DB_CHAINING OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET FILESTREAM( NON_TRANSACTED_ACCESS = OFF )<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET TARGET_RECOVERY_TIME = 0 SECONDS<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET  READ_WRITE<br />
GO<br />
[/sql]</p>
<p>Now we will create the table we needed. As of now I am going to create the table <em>tblTags </em></p>
<p><strong>Create tables in database</strong></p>
<p>Below is the query to create the table <em>tblTags</em>.</p>
<p>[sql]<br />
USE [TrialsDB]<br />
GO</p>
<p>/****** Object:  Table [dbo].[tblTags]    Script Date: 23-Mar-16 5:01:22 PM ******/<br />
SET ANSI_NULLS ON<br />
GO</p>
<p>SET QUOTED_IDENTIFIER ON<br />
GO</p>
<p>CREATE TABLE [dbo].[tblTags](<br />
	[tagId] [int] IDENTITY(1,1) NOT NULL,<br />
	[tagName] [nvarchar](50) NOT NULL,<br />
	[tagDescription] [nvarchar](max) NULL,<br />
 CONSTRAINT [PK_tblTags] PRIMARY KEY CLUSTERED<br />
(<br />
	[tagId] ASC<br />
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]<br />
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]</p>
<p>GO<br />
[/sql]</p>
<p>Can we insert some data to the tables now?</p>
<p><strong>Insert data to table</strong></p>
<p>You can use the below query to insert the data to the table <em>tblTags</em></p>
<p>[sql]<br />
USE [TrialsDB]<br />
GO</p>
<p>INSERT INTO [dbo].[tblTags]<br />
           ([tagName]<br />
           ,[tagDescription])<br />
     VALUES<br />
           (&lt;tagName, nvarchar(50),&gt;<br />
           ,&lt;tagDescription, nvarchar(max),&gt;)<br />
GO<br />
[/sql] </p>
<p>Next thing we are going to do is creating a ADO.NET Entity Data Model. </p>
<p><strong>Create Entity Data Model</strong></p>
<p>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. Here I gave <em>Dashboard</em> for our Entity data model name. Now you can see a file with edmx extension have been created.<br />
Now will create our Web API controller. </p>
<p><strong>Create Web API Controller</strong></p>
<p>To create a Web API controller, just right click on your controller folder and click Add -> Controller -> Select Web API 2 controller with actions, using Entity Framework.</p>
<p><div id="attachment_11401" style="width: 660px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/Web-API-2-Controller-With-Actions-Using-Entity-Framework-e1458709497551.png"><img decoding="async" aria-describedby="caption-attachment-11401" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/Web-API-2-Controller-With-Actions-Using-Entity-Framework-e1458709497551.png" alt="Web API 2 Controller With Actions Using Entity Framework" width="650" height="448" class="size-full wp-image-11401" srcset="/wp-content/uploads/2016/03/Web-API-2-Controller-With-Actions-Using-Entity-Framework-e1458709497551.png 650w, /wp-content/uploads/2016/03/Web-API-2-Controller-With-Actions-Using-Entity-Framework-e1458709497551-300x207.png 300w, /wp-content/uploads/2016/03/Web-API-2-Controller-With-Actions-Using-Entity-Framework-e1458709497551-160x110.png 160w, /wp-content/uploads/2016/03/Web-API-2-Controller-With-Actions-Using-Entity-Framework-e1458709497551-400x276.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><p id="caption-attachment-11401" class="wp-caption-text">Web API 2 Controller With Actions Using Entity Framework</p></div></p>
<p>Now select <em>tblTag (CachingInWebAPI.Models)</em> as our Model class and <em>TrialsDBEntities (CachingInWebAPI.Models)</em> as data context class. </p>
<p>As you can see It has been given the name of our controller as <em>tblTags</em>. Here I am not going to change that, if you wish to change, you can do that.</p>
<p>Now you will be given the following codes in our new Web API controller.</p>
<p>[csharp]<br />
using System;<br />
using System.Collections.Generic;<br />
using System.Data;<br />
using System.Data.Entity;<br />
using System.Data.Entity.Infrastructure;<br />
using System.Linq;<br />
using System.Net;<br />
using System.Net.Http;<br />
using System.Web.Http;<br />
using System.Web.Http.Description;<br />
using CachingInWebAPI.Models;</p>
<p>namespace CachingInWebAPI.Controllers<br />
{<br />
    public class tblTagsController : ApiController<br />
    {<br />
        private TrialsDBEntities db = new TrialsDBEntities();</p>
<p>        // GET: api/tblTags<br />
        public IQueryable&lt;tblTag&gt; GettblTags()<br />
        {<br />
            return db.tblTags;<br />
        }</p>
<p>        // GET: api/tblTags/5<br />
        [ResponseType(typeof(tblTag))]<br />
        public IHttpActionResult GettblTag(int id)<br />
        {<br />
            tblTag tblTag = db.tblTags.Find(id);<br />
            if (tblTag == null)<br />
            {<br />
                return NotFound();<br />
            }</p>
<p>            return Ok(tblTag);<br />
        }</p>
<p>        // PUT: api/tblTags/5<br />
        [ResponseType(typeof(void))]<br />
        public IHttpActionResult PuttblTag(int id, tblTag tblTag)<br />
        {<br />
            if (!ModelState.IsValid)<br />
            {<br />
                return BadRequest(ModelState);<br />
            }</p>
<p>            if (id != tblTag.tagId)<br />
            {<br />
                return BadRequest();<br />
            }</p>
<p>            db.Entry(tblTag).State = EntityState.Modified;</p>
<p>            try<br />
            {<br />
                db.SaveChanges();<br />
            }<br />
            catch (DbUpdateConcurrencyException)<br />
            {<br />
                if (!tblTagExists(id))<br />
                {<br />
                    return NotFound();<br />
                }<br />
                else<br />
                {<br />
                    throw;<br />
                }<br />
            }</p>
<p>            return StatusCode(HttpStatusCode.NoContent);<br />
        }</p>
<p>        // POST: api/tblTags<br />
        [ResponseType(typeof(tblTag))]<br />
        public IHttpActionResult PosttblTag(tblTag tblTag)<br />
        {<br />
            if (!ModelState.IsValid)<br />
            {<br />
                return BadRequest(ModelState);<br />
            }</p>
<p>            db.tblTags.Add(tblTag);<br />
            db.SaveChanges();</p>
<p>            return CreatedAtRoute(&quot;DefaultApi&quot;, new { id = tblTag.tagId }, tblTag);<br />
        }</p>
<p>        // DELETE: api/tblTags/5<br />
        [ResponseType(typeof(tblTag))]<br />
        public IHttpActionResult DeletetblTag(int id)<br />
        {<br />
            tblTag tblTag = db.tblTags.Find(id);<br />
            if (tblTag == null)<br />
            {<br />
                return NotFound();<br />
            }</p>
<p>            db.tblTags.Remove(tblTag);<br />
            db.SaveChanges();</p>
<p>            return Ok(tblTag);<br />
        }</p>
<p>        protected override void Dispose(bool disposing)<br />
        {<br />
            if (disposing)<br />
            {<br />
                db.Dispose();<br />
            }<br />
            base.Dispose(disposing);<br />
        }</p>
<p>        private bool tblTagExists(int id)<br />
        {<br />
            return db.tblTags.Count(e =&gt; e.tagId == id) &gt; 0;<br />
        }<br />
    }<br />
}<br />
[/csharp]</p>
<p>As we are not going to use only read operation, you can remove other functionalities and keep only <em>Get </em>methods for now.</p>
<p>[csharp]<br />
 // GET: api/tblTags<br />
        public IQueryable&lt;tblTag&gt; GettblTags()<br />
        {<br />
            return db.tblTags;<br />
        }<br />
[/csharp]</p>
<p>So the coding part to fetch the data from database is ready, now we need to check whether our Web API is ready for action!. To check that, you just need to run the URL <em>http://localhost:4832/api/tblTags</em>. Here <em>tblTags</em> is our Web API controller name. I hope you get the data as a result.</p>
<p><div id="attachment_11413" style="width: 660px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/Web_API_Result-e1458733092316.png"><img decoding="async" aria-describedby="caption-attachment-11413" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/Web_API_Result-e1458733092316.png" alt="Web_API_Result" width="650" height="342" class="size-full wp-image-11413" srcset="/wp-content/uploads/2016/03/Web_API_Result-e1458733092316.png 650w, /wp-content/uploads/2016/03/Web_API_Result-e1458733092316-300x158.png 300w, /wp-content/uploads/2016/03/Web_API_Result-e1458733092316-600x315.png 600w, /wp-content/uploads/2016/03/Web_API_Result-e1458733092316-400x210.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><p id="caption-attachment-11413" class="wp-caption-text">Web_API_Result</p></div></p>
<p>Now we will start testing our caching. For that please import the namespace <em>System.Runtime.Caching;</em></p>
<p>[csharp]<br />
using System.Runtime.Caching;<br />
[/csharp]</p>
<p>Next we will create an instance of <em>MemoryCache </em>class.</p>
<p><div id="attachment_11415" style="width: 664px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/MemoryCache_Tooltip_.png"><img decoding="async" aria-describedby="caption-attachment-11415" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/MemoryCache_Tooltip_.png" alt="MemoryCache_Tooltip_" width="654" height="102" class="size-full wp-image-11415" srcset="/wp-content/uploads/2016/03/MemoryCache_Tooltip_.png 654w, /wp-content/uploads/2016/03/MemoryCache_Tooltip_-300x47.png 300w, /wp-content/uploads/2016/03/MemoryCache_Tooltip_-400x62.png 400w" sizes="(max-width: 654px) 100vw, 654px" /></a><p id="caption-attachment-11415" class="wp-caption-text">MemoryCache_Tooltip_</p></div></p>
<p>As you can see there are four possible settings we can set in <em>MemoryCache </em> class.</p>
<p><div id="attachment_11416" style="width: 660px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/MemoryCache_Settings-e1458734646751.png"><img decoding="async" aria-describedby="caption-attachment-11416" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/MemoryCache_Settings-e1458734646751.png" alt="MemoryCache_Settings" width="650" height="123" class="size-full wp-image-11416" srcset="/wp-content/uploads/2016/03/MemoryCache_Settings-e1458734646751.png 650w, /wp-content/uploads/2016/03/MemoryCache_Settings-e1458734646751-300x57.png 300w, /wp-content/uploads/2016/03/MemoryCache_Settings-e1458734646751-400x76.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><p id="caption-attachment-11416" class="wp-caption-text">MemoryCache_Settings</p></div></p>
<p>Now we can add MemoryCache as follows. </p>
<p>[csharp]<br />
public IQueryable&lt;tblTag&gt; GettblTags()<br />
        {<br />
            var ca = db.tblTags;<br />
            memCache.Add(&quot;tag&quot;, ca, DateTimeOffset.UtcNow.AddMinutes(5));<br />
            return db.tblTags;<br />
        }<br />
[/csharp]</p>
<p><div id="attachment_11417" style="width: 660px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/MemoryCache_Add-e1458734908183.png"><img decoding="async" aria-describedby="caption-attachment-11417" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/MemoryCache_Add-e1458734908183.png" alt="MemoryCache_Add" width="650" height="70" class="size-full wp-image-11417" srcset="/wp-content/uploads/2016/03/MemoryCache_Add-e1458734908183.png 650w, /wp-content/uploads/2016/03/MemoryCache_Add-e1458734908183-300x32.png 300w, /wp-content/uploads/2016/03/MemoryCache_Add-e1458734908183-400x43.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><p id="caption-attachment-11417" class="wp-caption-text">MemoryCache_Add</p></div></p>
<p>Here &#8220;tag&#8221; is my key and &#8220;ca&#8221; is my values and DateTimeOffset.UtcNow.AddMinutes(5) is for setting the cache for five minutes from now. </p>
<p>Shall we check how it works now? To check whether the content has been added to the cache we need to use the Get method, please see the code block below. </p>
<p>[csharp]<br />
var res = memCache.Get(&quot;tag&quot;);<br />
            if (res != null)<br />
            {<br />
                return res;<br />
            }<br />
            else {<br />
                var ca = db.tblTags;<br />
                memCache.Add(&quot;tag&quot;, ca, DateTimeOffset.UtcNow.AddMinutes(5));<br />
                return db.tblTags;<br />
            }<br />
[/csharp]</p>
<p>We will get the cache values in the variable res, remember this values will be there only for five minutes. You can always change that as per need. If the value is not null, we will just return it and do the manipulation and if it is null we will go ahead and fetch the data from database and add the value to cache. Now please run your API by running the URL <em>http://localhost:4832/api/tblTags</em>. </p>
<p><div id="attachment_11418" style="width: 634px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/Cache_Value_Null.png"><img decoding="async" aria-describedby="caption-attachment-11418" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/Cache_Value_Null.png" alt="Cache_Value_Null" width="624" height="215" class="size-full wp-image-11418" srcset="/wp-content/uploads/2016/03/Cache_Value_Null.png 624w, /wp-content/uploads/2016/03/Cache_Value_Null-300x103.png 300w, /wp-content/uploads/2016/03/Cache_Value_Null-620x215.png 620w, /wp-content/uploads/2016/03/Cache_Value_Null-400x138.png 400w" sizes="(max-width: 624px) 100vw, 624px" /></a><p id="caption-attachment-11418" class="wp-caption-text">Cache_Value_Null</p></div></p>
<p>You can see that we are setting the value to memCache as the <em>memCache.Get(&#8220;tag&#8221;)</em> is null. </p>
<p><div id="attachment_11419" style="width: 606px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/Cache_Value_Not_Null.png"><img decoding="async" aria-describedby="caption-attachment-11419" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/Cache_Value_Not_Null.png" alt="Cache_Value_Not_Null" width="596" height="215" class="size-full wp-image-11419" srcset="/wp-content/uploads/2016/03/Cache_Value_Not_Null.png 596w, /wp-content/uploads/2016/03/Cache_Value_Not_Null-300x108.png 300w, /wp-content/uploads/2016/03/Cache_Value_Not_Null-400x144.png 400w" sizes="(max-width: 596px) 100vw, 596px" /></a><p id="caption-attachment-11419" class="wp-caption-text">Cache_Value_Not_Null</p></div></p>
<p>So we just tried to load the same Web API URL within five minutes, so we gets values from <em>memCache.Get(&#8220;tag&#8221;)</em>. Sounds good?</p>
<p>There is an option to remove our cache too, we will see that now. We will use the <em>Remove</em> function for the same. First we will check whether the key is available in the <em>MemoryCache</em>, if it is available we will remove that.</p>
<p>[csharp]<br />
//This is to remove the MemoryCache &#8211; start<br />
                if (memCache.Contains(&quot;tag&quot;))<br />
                {<br />
                    memCache.Remove(&quot;tag&quot;);<br />
                }<br />
                //This is to remove the MemoryCache &#8211; end<br />
[/csharp]</p>
<p><div id="attachment_11420" style="width: 660px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/MemoryCache_Remove-e1458737311814.png"><img decoding="async" aria-describedby="caption-attachment-11420" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/MemoryCache_Remove-e1458737311814.png" alt="MemoryCache_Remove" width="650" height="299" class="size-full wp-image-11420" srcset="/wp-content/uploads/2016/03/MemoryCache_Remove-e1458737311814.png 650w, /wp-content/uploads/2016/03/MemoryCache_Remove-e1458737311814-300x138.png 300w, /wp-content/uploads/2016/03/MemoryCache_Remove-e1458737311814-400x184.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><p id="caption-attachment-11420" class="wp-caption-text">MemoryCache_Remove</p></div></p>
<p>We have done everything!. That&#8217;s fantastic right? Have a happy coding.</p>
<p><strong>Conclusion</strong></p>
<p>Did I miss anything that you may think which is needed? Did you try Web API yet? Have you ever wanted to do caching in Web API? Could you find this post as useful? I hope you liked this article. Please share me your valuable suggestions and feedback.</p>
<p><strong>Your turn. What do you think?</strong></p>
<p>A blog isn&#8217;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.</p>
<p>Kindest Regards<br />
Sibeesh Venu</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.sibeeshpassion.com/caching-in-web-api/feed/</wfw:commentRss>
			<slash:comments>7</slash:comments>
		
		
			</item>
		<item>
		<title>Angular JS AutoComplete In MVC With Web API</title>
		<link>https://www.sibeeshpassion.com/angular-js-autocomplete-in-mvc-with-web-api/</link>
					<comments>https://www.sibeeshpassion.com/angular-js-autocomplete-in-mvc-with-web-api/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Thu, 24 Mar 2016 00:00:33 +0000</pubDate>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Angular]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[Web API]]></category>
		<category><![CDATA[Angular JS]]></category>
		<category><![CDATA[Angular JS AutoComplete]]></category>
		<category><![CDATA[AutoComplete]]></category>
		<category><![CDATA[Autocomplete With Web API]]></category>
		<category><![CDATA[MVC]]></category>
		<guid isPermaLink="false">http://sibeecst_passion.com/?p=11393</guid>

					<description><![CDATA[In this article we will learn how we can create Angular JS autoComplete text box with the data from SQL Server database. We use MVC architecture with Web API and Angular JS to fetch the data and do all the manipulations. I am creating this application in Visual Studio 2015. 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 Now we will go and create our application. I hope you will like this. Download the source code You can always download [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>In this article we will learn how we can create Angular JS autoComplete text box with the data from <a href="http://sibeeshpassion.com/category/SQL/" target="_blank" rel="noopener">SQL </a>Server database. We use MVC architecture with Web API and Angular JS to fetch the data and do all the manipulations. I am creating this application in Visual Studio 2015. You can always get the tips/tricks/blogs about these mentioned technologies from the links given below. </p>
<li><a href="http://sibeeshpassion.com/category/angularjs/" target="_blank" rel="noopener">AngularJS Tips, Tricks, Blogs</a></li>
<li><a href="http://sibeeshpassion.com/category/mvc/" target="_blank" rel="noopener">MVC Tips, Tricks, Blogs</a></li>
<li><a href="http://sibeeshpassion.com/category/web-api/" target="_blank" rel="noopener">Web API Tips, Tricks, Blogs</a></li>
<p>Now we will go and create our application. I hope you will like this. </p>
<p><strong>Download the source code</strong></p>
<p>You can always download the source code here.</p>
<li><a href="https://code.msdn.microsoft.com/Angular-JS-AutoComplete-In-96a92c45" target="_blank" rel="noopener">Angular JS Autocomplete In MVC</a></li>
<li><a href="http://sibeeshpassion.com/Download/MyDashboardSQLScript.rar" target="_blank" rel="noopener">SQL Scripts With Insert Queries</a></li>
<p><strong>Background</strong></p>
<p>For the past few days I am experiment few things in Angular JS. Here we are going to see a demo of how to use Angular JS autocomplete in MVC with Web API to fetch the data from database. Once we are done, this is how our applications output will be. </p>
<p><div id="attachment_11394" style="width: 435px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/Angular_JS_Autocomplete_In_MVC_With_Web_API_Output_.png"><img decoding="async" aria-describedby="caption-attachment-11394" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/Angular_JS_Autocomplete_In_MVC_With_Web_API_Output_.png" alt="Angular_JS_Autocomplete_In_MVC_With_Web_API_Output_" width="425" height="266" class="size-full wp-image-11394" srcset="/wp-content/uploads/2016/03/Angular_JS_Autocomplete_In_MVC_With_Web_API_Output_.png 425w, /wp-content/uploads/2016/03/Angular_JS_Autocomplete_In_MVC_With_Web_API_Output_-300x188.png 300w, /wp-content/uploads/2016/03/Angular_JS_Autocomplete_In_MVC_With_Web_API_Output_-400x250.png 400w" sizes="(max-width: 425px) 100vw, 425px" /></a><p id="caption-attachment-11394" class="wp-caption-text">Angular_JS_Autocomplete_In_MVC_With_Web_API_Output_</p></div></p>
<p><div id="attachment_11395" style="width: 437px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/Angular_JS_Autocomplete_In_MVC_With_Web_API_Output_With_Filter_.png"><img decoding="async" aria-describedby="caption-attachment-11395" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/Angular_JS_Autocomplete_In_MVC_With_Web_API_Output_With_Filter_.png" alt="Angular_JS_Autocomplete_In_MVC_With_Web_API_Output_With_Filter_" width="427" height="361" class="size-full wp-image-11395" srcset="/wp-content/uploads/2016/03/Angular_JS_Autocomplete_In_MVC_With_Web_API_Output_With_Filter_.png 427w, /wp-content/uploads/2016/03/Angular_JS_Autocomplete_In_MVC_With_Web_API_Output_With_Filter_-300x254.png 300w, /wp-content/uploads/2016/03/Angular_JS_Autocomplete_In_MVC_With_Web_API_Output_With_Filter_-400x338.png 400w" sizes="(max-width: 427px) 100vw, 427px" /></a><p id="caption-attachment-11395" class="wp-caption-text">Angular_JS_Autocomplete_In_MVC_With_Web_API_Output_With_Filter_</p></div></p>
<p><strong>Create a MVC application</strong></p>
<p>Click File-> New-> Project then select MVC application. From the following pop up we will select the template as empty and select the core references and folders for MVC. </p>
<p><div id="attachment_11405" style="width: 660px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/Empty-Template-With-MVC-And-Web-API-Folders-e1458711950206.png"><img decoding="async" aria-describedby="caption-attachment-11405" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/Empty-Template-With-MVC-And-Web-API-Folders-e1458711950206.png" alt="Empty Template With MVC And Web API Folders" width="650" height="484" class="size-full wp-image-11405" srcset="/wp-content/uploads/2016/03/Empty-Template-With-MVC-And-Web-API-Folders-e1458711950206.png 650w, /wp-content/uploads/2016/03/Empty-Template-With-MVC-And-Web-API-Folders-e1458711950206-300x223.png 300w, /wp-content/uploads/2016/03/Empty-Template-With-MVC-And-Web-API-Folders-e1458711950206-400x298.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><p id="caption-attachment-11405" class="wp-caption-text">Empty Template With MVC And Web API Folders</p></div></p>
<p>Once you click OK, a project with MVC like folder structure with core references will be created for you.</p>
<p><div id="attachment_11362" style="width: 277px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/Folder-Structure-And-References-For-Empty-MVC-Project.png"><img decoding="async" aria-describedby="caption-attachment-11362" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/Folder-Structure-And-References-For-Empty-MVC-Project.png" alt="Folder Structure And References For Empty MVC Project" width="267" height="367" class="size-full wp-image-11362" srcset="/wp-content/uploads/2016/03/Folder-Structure-And-References-For-Empty-MVC-Project.png 267w, /wp-content/uploads/2016/03/Folder-Structure-And-References-For-Empty-MVC-Project-218x300.png 218w" sizes="(max-width: 267px) 100vw, 267px" /></a><p id="caption-attachment-11362" class="wp-caption-text">Folder Structure And References For Empty MVC Project</p></div></p>
<p>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. </p>
<li>Angular JS</li>
<li>jQuery</li>
<p>You can all the items mentioned above from NuGet. Right click on your project name and select Manage NuGet packages.</p>
<p><div id="attachment_11407" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/Manage-NuGet-Package-Window-e1458712083925.png"><img decoding="async" aria-describedby="caption-attachment-11407" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/Manage-NuGet-Package-Window-1024x407.png" alt="Manage NuGet Package Window" width="634" height="252" class="size-large wp-image-11407" /></a><p id="caption-attachment-11407" class="wp-caption-text">Manage NuGet Package Window</p></div></p>
<p>Once you have installed those items, please make sure that all the items(jQuery, Angular JS files) are loaded in your scripts folder. </p>
<p><strong>Using the code</strong></p>
<p>As I have said before, we are going to use Angular JS for our client side operations, so it is better to create the Angular JS script files first right? Just to make sure that we have got all the required things :). For that I am going to create a script file called <em>Home.js</em> in which we will write our scripts. Sounds good? Yes, we have set everything to get started our coding. Now we will create a Web API controller and get the data from database in JSON format. Let&#8217;s start then.</p>
<p>We will set up our database first so that we can create Entity Model for our application later. </p>
<p><strong>Create a database</strong></p>
<p>The following query can be used to create a database in your SQL Server.</p>
<p>[sql]<br />
USE [master]<br />
GO</p>
<p>/****** Object:  Database [TrialsDB]<br />
CREATE DATABASE [TrialsDB]<br />
 CONTAINMENT = NONE<br />
 ON  PRIMARY<br />
( NAME = N&#8217;TrialsDB&#8217;, FILENAME = N&#8217;C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\TrialsDB.mdf&#8217; , SIZE = 3072KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )<br />
 LOG ON<br />
( NAME = N&#8217;TrialsDB_log&#8217;, FILENAME = N&#8217;C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\TrialsDB_log.ldf&#8217; , SIZE = 1024KB , MAXSIZE = 2048GB , FILEGROWTH = 10%)<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET COMPATIBILITY_LEVEL = 110<br />
GO</p>
<p>IF (1 = FULLTEXTSERVICEPROPERTY(&#8216;IsFullTextInstalled&#8217;))<br />
begin<br />
EXEC [TrialsDB].[dbo].[sp_fulltext_database] @action = &#8216;enable&#8217;<br />
end<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET ANSI_NULL_DEFAULT OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET ANSI_NULLS OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET ANSI_PADDING OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET ANSI_WARNINGS OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET ARITHABORT OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET AUTO_CLOSE OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET AUTO_CREATE_STATISTICS ON<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET AUTO_SHRINK OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET AUTO_UPDATE_STATISTICS ON<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET CURSOR_CLOSE_ON_COMMIT OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET CURSOR_DEFAULT  GLOBAL<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET CONCAT_NULL_YIELDS_NULL OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET NUMERIC_ROUNDABORT OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET QUOTED_IDENTIFIER OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET RECURSIVE_TRIGGERS OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET  DISABLE_BROKER<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET AUTO_UPDATE_STATISTICS_ASYNC OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET DATE_CORRELATION_OPTIMIZATION OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET TRUSTWORTHY OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET ALLOW_SNAPSHOT_ISOLATION OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET PARAMETERIZATION SIMPLE<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET READ_COMMITTED_SNAPSHOT OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET HONOR_BROKER_PRIORITY OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET RECOVERY FULL<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET  MULTI_USER<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET PAGE_VERIFY CHECKSUM<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET DB_CHAINING OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET FILESTREAM( NON_TRANSACTED_ACCESS = OFF )<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET TARGET_RECOVERY_TIME = 0 SECONDS<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET  READ_WRITE<br />
GO<br />
[/sql]</p>
<p>Now we will create the table we needed. As of now I am going to create the table <em>Products </em></p>
<p><strong>Create tables in database</strong></p>
<p>Below is the query to create the table Product.</p>
<p>[sql]<br />
USE [TrialsDB]<br />
GO</p>
<p>/****** Object:  Table [dbo].[Product]<br />
SET ANSI_NULLS ON<br />
GO</p>
<p>SET QUOTED_IDENTIFIER ON<br />
GO</p>
<p>CREATE TABLE [dbo].[Product](<br />
	[ProductID] [int] NOT NULL,<br />
	[Name] [nvarchar](max) NOT NULL,<br />
	[ProductNumber] [nvarchar](25) NOT NULL,<br />
	[MakeFlag] [bit] NOT NULL,<br />
	[FinishedGoodsFlag] [bit] NOT NULL,<br />
	[Color] [nvarchar](15) NULL,<br />
	[SafetyStockLevel] [smallint] NOT NULL,<br />
	[ReorderPoint] [smallint] NOT NULL,<br />
	[StandardCost] [money] NOT NULL,<br />
	[ListPrice] [money] NOT NULL,<br />
	[Size] [nvarchar](5) NULL,<br />
	[SizeUnitMeasureCode] [nchar](3) NULL,<br />
	[WeightUnitMeasureCode] [nchar](3) NULL,<br />
	[Weight] [decimal](8, 2) NULL,<br />
	[DaysToManufacture] [int] NOT NULL,<br />
	[ProductLine] [nchar](2) NULL,<br />
	[Class] [nchar](2) NULL,<br />
	[Style] [nchar](2) NULL,<br />
	[ProductSubcategoryID] [int] NULL,<br />
	[ProductModelID] [int] NULL,<br />
	[SellStartDate] [datetime] NOT NULL,<br />
	[SellEndDate] [datetime] NULL,<br />
	[DiscontinuedDate] [datetime] NULL,<br />
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,<br />
	[ModifiedDate] [datetime] NOT NULL<br />
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]</p>
<p>GO<br />
[/sql]</p>
<p>Can we insert some data to the tables now?</p>
<p><strong>Insert data to table</strong></p>
<p>You can use the below query to insert the data to the table <em>Product</em></p>
<p>[sql]<br />
USE [TrialsDB]<br />
GO</p>
<p>INSERT INTO [dbo].[Product]<br />
           ([ProductID]<br />
           ,[Name]<br />
           ,[ProductNumber]<br />
           ,[MakeFlag]<br />
           ,[FinishedGoodsFlag]<br />
           ,[Color]<br />
           ,[SafetyStockLevel]<br />
           ,[ReorderPoint]<br />
           ,[StandardCost]<br />
           ,[ListPrice]<br />
           ,[Size]<br />
           ,[SizeUnitMeasureCode]<br />
           ,[WeightUnitMeasureCode]<br />
           ,[Weight]<br />
           ,[DaysToManufacture]<br />
           ,[ProductLine]<br />
           ,[Class]<br />
           ,[Style]<br />
           ,[ProductSubcategoryID]<br />
           ,[ProductModelID]<br />
           ,[SellStartDate]<br />
           ,[SellEndDate]<br />
           ,[DiscontinuedDate]<br />
           ,[rowguid]<br />
           ,[ModifiedDate])<br />
     VALUES<br />
           (&lt;ProductID, int,&gt;<br />
           ,&lt;Name, nvarchar(max),&gt;<br />
           ,&lt;ProductNumber, nvarchar(25),&gt;<br />
           ,&lt;MakeFlag, bit,&gt;<br />
           ,&lt;FinishedGoodsFlag, bit,&gt;<br />
           ,&lt;Color, nvarchar(15),&gt;<br />
           ,&lt;SafetyStockLevel, smallint,&gt;<br />
           ,&lt;ReorderPoint, smallint,&gt;<br />
           ,&lt;StandardCost, money,&gt;<br />
           ,&lt;ListPrice, money,&gt;<br />
           ,&lt;Size, nvarchar(5),&gt;<br />
           ,&lt;SizeUnitMeasureCode, nchar(3),&gt;<br />
           ,&lt;WeightUnitMeasureCode, nchar(3),&gt;<br />
           ,&lt;Weight, decimal(8,2),&gt;<br />
           ,&lt;DaysToManufacture, int,&gt;<br />
           ,&lt;ProductLine, nchar(2),&gt;<br />
           ,&lt;Class, nchar(2),&gt;<br />
           ,&lt;Style, nchar(2),&gt;<br />
           ,&lt;ProductSubcategoryID, int,&gt;<br />
           ,&lt;ProductModelID, int,&gt;<br />
           ,&lt;SellStartDate, datetime,&gt;<br />
           ,&lt;SellEndDate, datetime,&gt;<br />
           ,&lt;DiscontinuedDate, datetime,&gt;<br />
           ,&lt;rowguid, uniqueidentifier,&gt;<br />
           ,&lt;ModifiedDate, datetime,&gt;)<br />
GO<br />
[/sql] </p>
<p>So let us say, we have inserted the data as follows. If you feel bored of inserting data manually, you can always run the SQL script file attached which has the insertion queries. Just run that, you will be all OK. If you don&#8217;t know how to generate SQL scripts with data, I strongly recommend you to have a read <a href="http://sibeeshpassion.com/generate-database-scripts-with-data-in-sql-server/" target="_blank" rel="noopener">here</a></p>
<p>Next thing we are going to do is creating a ADO.NET Entity Data Model. </p>
<p><strong>Create Entity Data Model</strong></p>
<p>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. Here I gave <em>Dashboard</em> for our Entity data model name. Now you can see a file with edmx extension have been created. If you open that file, you can see as below. </p>
<p><div id="attachment_11400" style="width: 274px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/Entity-Data-Model-Product-Table.png"><img decoding="async" aria-describedby="caption-attachment-11400" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/Entity-Data-Model-Product-Table.png" alt="Entity Data Model Product Table" width="264" height="663" class="size-full wp-image-11400" srcset="/wp-content/uploads/2016/03/Entity-Data-Model-Product-Table.png 264w, /wp-content/uploads/2016/03/Entity-Data-Model-Product-Table-119x300.png 119w, /wp-content/uploads/2016/03/Entity-Data-Model-Product-Table-239x600.png 239w" sizes="(max-width: 264px) 100vw, 264px" /></a><p id="caption-attachment-11400" class="wp-caption-text">Entity Data Model Product Table</p></div></p>
<p>Now will create our Web API controller. </p>
<p><strong>Create Web API Controller</strong></p>
<p>To create a Web API controller, just right click on your controller folder and click Add -> Controller -> Select Web API 2 controller with actions, using Entity Framework.</p>
<p><div id="attachment_11401" style="width: 660px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/Web-API-2-Controller-With-Actions-Using-Entity-Framework-e1458709497551.png"><img decoding="async" aria-describedby="caption-attachment-11401" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/Web-API-2-Controller-With-Actions-Using-Entity-Framework-e1458709497551.png" alt="Web API 2 Controller With Actions Using Entity Framework" width="650" height="448" class="size-full wp-image-11401" srcset="/wp-content/uploads/2016/03/Web-API-2-Controller-With-Actions-Using-Entity-Framework-e1458709497551.png 650w, /wp-content/uploads/2016/03/Web-API-2-Controller-With-Actions-Using-Entity-Framework-e1458709497551-300x207.png 300w, /wp-content/uploads/2016/03/Web-API-2-Controller-With-Actions-Using-Entity-Framework-e1458709497551-160x110.png 160w, /wp-content/uploads/2016/03/Web-API-2-Controller-With-Actions-Using-Entity-Framework-e1458709497551-400x276.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><p id="caption-attachment-11401" class="wp-caption-text">Web API 2 Controller With Actions Using Entity Framework</p></div></p>
<p>Now select <em>Product (AngularJSAutocompleteInMVCWithWebAPI.Models)</em> as our Model class and <em>TrialsDBEntities (AngularJSAutocompleteInMVCWithWebAPI.Models)</em> as data context class. </p>
<p><div id="attachment_11402" style="width: 635px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/Model-Class-And-Data-Context-Class.png"><img decoding="async" aria-describedby="caption-attachment-11402" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/Model-Class-And-Data-Context-Class.png" alt="Model Class And Data Context Class" width="625" height="267" class="size-full wp-image-11402" srcset="/wp-content/uploads/2016/03/Model-Class-And-Data-Context-Class.png 625w, /wp-content/uploads/2016/03/Model-Class-And-Data-Context-Class-300x128.png 300w, /wp-content/uploads/2016/03/Model-Class-And-Data-Context-Class-400x171.png 400w" sizes="(max-width: 625px) 100vw, 625px" /></a><p id="caption-attachment-11402" class="wp-caption-text">Model Class And Data Context Class</p></div></p>
<p>As you can see It has been given the name of our controller as <em>Products</em>. Here I am not going to change that, if you wish to change, you can do that.</p>
<p>Now you will be given the following codes in our new Web API controller.</p>
<p>[csharp]<br />
using System;<br />
using System.Collections.Generic;<br />
using System.Data;<br />
using System.Data.Entity;<br />
using System.Data.Entity.Infrastructure;<br />
using System.Linq;<br />
using System.Net;<br />
using System.Net.Http;<br />
using System.Web.Http;<br />
using System.Web.Http.Description;<br />
using AngularJSAutocompleteInMVCWithWebAPI.Models;</p>
<p>namespace AngularJSAutocompleteInMVCWithWebAPI.Controllers<br />
{<br />
    public class ProductsController : ApiController<br />
    {<br />
        private TrialsDBEntities db = new TrialsDBEntities();</p>
<p>        // GET: api/Products<br />
        public IQueryable&lt;Product&gt; GetProducts()<br />
        {<br />
            return db.Products;<br />
        }</p>
<p>        // GET: api/Products/5<br />
        [ResponseType(typeof(Product))]<br />
        public IHttpActionResult GetProduct(int id)<br />
        {<br />
            Product product = db.Products.Find(id);<br />
            if (product == null)<br />
            {<br />
                return NotFound();<br />
            }</p>
<p>            return Ok(product);<br />
        }</p>
<p>        // PUT: api/Products/5<br />
        [ResponseType(typeof(void))]<br />
        public IHttpActionResult PutProduct(int id, Product product)<br />
        {<br />
            if (!ModelState.IsValid)<br />
            {<br />
                return BadRequest(ModelState);<br />
            }</p>
<p>            if (id != product.ProductID)<br />
            {<br />
                return BadRequest();<br />
            }</p>
<p>            db.Entry(product).State = EntityState.Modified;</p>
<p>            try<br />
            {<br />
                db.SaveChanges();<br />
            }<br />
            catch (DbUpdateConcurrencyException)<br />
            {<br />
                if (!ProductExists(id))<br />
                {<br />
                    return NotFound();<br />
                }<br />
                else<br />
                {<br />
                    throw;<br />
                }<br />
            }</p>
<p>            return StatusCode(HttpStatusCode.NoContent);<br />
        }</p>
<p>        // POST: api/Products<br />
        [ResponseType(typeof(Product))]<br />
        public IHttpActionResult PostProduct(Product product)<br />
        {<br />
            if (!ModelState.IsValid)<br />
            {<br />
                return BadRequest(ModelState);<br />
            }</p>
<p>            db.Products.Add(product);</p>
<p>            try<br />
            {<br />
                db.SaveChanges();<br />
            }<br />
            catch (DbUpdateException)<br />
            {<br />
                if (ProductExists(product.ProductID))<br />
                {<br />
                    return Conflict();<br />
                }<br />
                else<br />
                {<br />
                    throw;<br />
                }<br />
            }</p>
<p>            return CreatedAtRoute(&quot;DefaultApi&quot;, new { id = product.ProductID }, product);<br />
        }</p>
<p>        // DELETE: api/Products/5<br />
        [ResponseType(typeof(Product))]<br />
        public IHttpActionResult DeleteProduct(int id)<br />
        {<br />
            Product product = db.Products.Find(id);<br />
            if (product == null)<br />
            {<br />
                return NotFound();<br />
            }</p>
<p>            db.Products.Remove(product);<br />
            db.SaveChanges();</p>
<p>            return Ok(product);<br />
        }</p>
<p>        protected override void Dispose(bool disposing)<br />
        {<br />
            if (disposing)<br />
            {<br />
                db.Dispose();<br />
            }<br />
            base.Dispose(disposing);<br />
        }</p>
<p>        private bool ProductExists(int id)<br />
        {<br />
            return db.Products.Count(e =&gt; e.ProductID == id) &gt; 0;<br />
        }<br />
    }<br />
}<br />
[/csharp]</p>
<p>As we are not going to use only read operation, you can remove other functionalities and keep only <em>Get </em>methods.</p>
<p>[csharp]<br />
 // GET: api/Products<br />
        public IQueryable&lt;Product&gt; GetProducts()<br />
        {<br />
            return db.Products;<br />
        }<br />
[/csharp]</p>
<p>So the coding part to fetch the data from database is ready, now we need to check whether our Web API is ready for action!. To check that, you just need to run the URL <em>http://localhost:9038/api/products</em>. Here <em>products</em> is our Web API controller name. I hope you get the data as a result.</p>
<p><div id="attachment_11403" style="width: 660px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/Web-API-Result-e1458710180875.png"><img decoding="async" aria-describedby="caption-attachment-11403" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/Web-API-Result-e1458710180875.png" alt="Web API Result" width="650" height="588" class="size-full wp-image-11403" srcset="/wp-content/uploads/2016/03/Web-API-Result-e1458710180875.png 650w, /wp-content/uploads/2016/03/Web-API-Result-e1458710180875-300x271.png 300w, /wp-content/uploads/2016/03/Web-API-Result-e1458710180875-400x362.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><p id="caption-attachment-11403" class="wp-caption-text">Web API Result</p></div></p>
<p>Now we will go back to our angular JS file and consume this Web API. You need to change the scripts in the <em>Home.js</em> as follows.</p>
<p>[js]<br />
(function () {<br />
    &#8216;use strict&#8217;;<br />
    angular<br />
        .module(&#8216;MyApp&#8217;, [&#8216;ngMaterial&#8217;, &#8216;ngMessages&#8217;, &#8216;material.svgAssetsCache&#8217;])<br />
        .controller(&#8216;AutoCompleteCtrl&#8217;, AutoCompleteCtrl);<br />
    function AutoCompleteCtrl($http, $timeout, $q, $log) {<br />
        var self = this;<br />
        self.simulateQuery = true;<br />
        self.products = loadAllProducts($http);<br />
        self.querySearch = querySearch;<br />
        function querySearch(query) {<br />
            var results = query ? self.products.filter(createFilterFor(query)) : self.products, deferred;<br />
            if (self.simulateQuery) {<br />
                deferred = $q.defer();<br />
                $timeout(function () { deferred.resolve(results); }, Math.random() * 1000, false);<br />
                return deferred.promise;<br />
            } else {<br />
                return results;<br />
            }<br />
        }<br />
        function loadAllProducts($http) {<br />
            var allProducts = [];<br />
            var url = &#8221;;<br />
            var result = [];<br />
            url = &#8216;api/products&#8217;;<br />
            $http({<br />
                method: &#8216;GET&#8217;,<br />
                url: url,<br />
            }).then(function successCallback(response) {<br />
                allProducts = response.data;<br />
                angular.forEach(allProducts, function (product, key) {<br />
                    result.push(<br />
                        {<br />
                            value: product.Name.toLowerCase(),<br />
                            display: product.Name<br />
                        });<br />
                });<br />
            }, function errorCallback(response) {<br />
                console.log(&#8216;Oops! Something went wrong while fetching the data. Status Code: &#8216; + response.status + &#8216; Status statusText: &#8216; + response.statusText);<br />
            });<br />
            return result;<br />
        }<br />
        function createFilterFor(query) {<br />
            var lowercaseQuery = angular.lowercase(query);<br />
            return function filterFn(product) {<br />
                return (product.value.indexOf(lowercaseQuery) === 0);<br />
            };</p>
<p>        }<br />
    }<br />
})();<br />
[/js]</p>
<p>Here <em>MyApp</em> is our module name and <em>AutoCompleteCtrl</em> is our controller name. The function  <em>loadAllProducts</em> is for loading the products from database using <a href="http://sibeeshpassion.com/learning-angularjs-http/" target="_blank" rel="noopener">$http in Angular JS</a>. </p>
<p>Once our service is called, we will get the data in return. We will parse the same and store it in a variable for future use. We will loop through the same using <em>angular.forEach</em> and format as needed.</p>
<p>[js]<br />
angular.forEach(allProducts, function (product, key) {<br />
                    result.push(<br />
                        {<br />
                            value: product.Name.toLowerCase(),<br />
                            display: product.Name<br />
                        });<br />
                });<br />
[/js]</p>
<p>The function <em>querySearch</em> will be called when ever user search for any particular products. This we will call from the view as follows. </p>
<p>[html]<br />
md-items=&quot;item in ctrl.querySearch(ctrl.searchText)&quot;<br />
[/html]</p>
<p>Now we need a view to show our data right? Yes, we need a controller too!.</p>
<p><strong>Create a MVC controller</strong></p>
<p>To create a controller, we need to right click on the controller folder, Add &#8211; Controller. I hope you will be given a controller as follows. </p>
<p>[csharp]<br />
using System;<br />
using System.Collections.Generic;<br />
using System.Linq;<br />
using System.Web;<br />
using System.Web.Mvc;</p>
<p>namespace AngularJSAutocompleteInMVCWithWebAPI.Controllers<br />
{<br />
    public class HomeController : Controller<br />
    {<br />
        // GET: Home<br />
        public ActionResult Index()<br />
        {<br />
            return View();<br />
        }<br />
    }<br />
}<br />
[/csharp]</p>
<p>Here <em>Home</em> is our controller name. </p>
<p>Now we need a view right?</p>
<p><strong>Creating a view</strong></p>
<p>To create a view, just right click on your controller name -> Add View -> Add.</p>
<p><div id="attachment_11366" style="width: 635px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/Creating-a-view.png"><img decoding="async" aria-describedby="caption-attachment-11366" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/Creating-a-view.png" alt="Creating a view" width="625" height="398" class="size-full wp-image-11366" srcset="/wp-content/uploads/2016/03/Creating-a-view.png 625w, /wp-content/uploads/2016/03/Creating-a-view-300x191.png 300w, /wp-content/uploads/2016/03/Creating-a-view-400x255.png 400w" sizes="(max-width: 625px) 100vw, 625px" /></a><p id="caption-attachment-11366" class="wp-caption-text">Creating a view</p></div></p>
<p>Now in your view add the needed references.</p>
<p>[html]<br />
&lt;script src=&quot;~/scripts/angular.min.js&quot;&gt;&lt;/script&gt;<br />
&lt;script src=&quot;~/scripts/angular-route.min.js&quot;&gt;&lt;/script&gt;<br />
&lt;script src=&quot;~/scripts/angular-aria.min.js&quot;&gt;&lt;/script&gt;<br />
&lt;script src=&quot;~/scripts/angular-animate.min.js&quot;&gt;&lt;/script&gt;<br />
&lt;script src=&quot;~/scripts/angular-messages.min.js&quot;&gt;&lt;/script&gt;<br />
&lt;script src=&quot;~/scripts/angular-material.js&quot;&gt;&lt;/script&gt;<br />
&lt;script src=&quot;~/scripts/svg-assets-cache.js&quot;&gt;&lt;/script&gt;<br />
&lt;script src=&quot;~/scripts/Home.js&quot;&gt;&lt;/script&gt;<br />
[/html]</p>
<p>Once we add the references, we can call our Angular JS controller and change the view code as follows.</p>
<p>[html]<br />
&lt;div ng-controller=&quot;AutoCompleteCtrl as ctrl&quot; layout=&quot;column&quot; ng-cloak=&quot;&quot; class=&quot;autocompletedemoBasicUsage&quot; ng-app=&quot;MyApp&quot; style=&quot;width: 34%;&quot;&gt;<br />
    &lt;md-content class=&quot;md-padding&quot;&gt;<br />
        &lt;form ng-submit=&quot;$event.preventDefault()&quot;&gt;<br />
            &lt;md-autocomplete md-no-cache=&quot;false&quot; md-selected-item=&quot;ctrl.selectedItem&quot; md-search-text=&quot;ctrl.searchText&quot; md-items=&quot;item in ctrl.querySearch(ctrl.searchText)&quot; md-item-text=&quot;item.display&quot; md-min-length=&quot;0&quot; placeholder=&quot;Search for products here!.&quot;&gt;<br />
                &lt;md-item-template&gt;<br />
                    &lt;span md-highlight-text=&quot;ctrl.searchText&quot; md-highlight-flags=&quot;^i&quot;&gt;{{item.display}}&lt;/span&gt;<br />
                &lt;/md-item-template&gt;<br />
                &lt;md-not-found&gt;<br />
                    No matching &quot;{{ctrl.searchText}}&quot; were found.<br />
                &lt;/md-not-found&gt;<br />
            &lt;/md-autocomplete&gt;<br />
        &lt;/form&gt;<br />
    &lt;/md-content&gt;<br />
&lt;/div&gt;<br />
[/html]</p>
<p>Here <em>md-autocomplete</em> will cache the result we gets from database to avoid the unwanted hits to the database. This we can disable/enable by the help of <em>md-no-cache</em>. Now if you run your application, you can see our Web API call works fine and successfully get the data. But the page looks clumsy right? For this you must add a style sheet <em>angular-material.css</em>.</p>
<p>[html]<br />
&lt;link href=&quot;~/Content/angular-material.css&quot; rel=&quot;stylesheet&quot; /&gt;<br />
[/html]</p>
<p>Now run your page again, I am sure you will get the output as follows. </p>
<p><strong>Output</strong></p>
<p><div id="attachment_11394" style="width: 435px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/Angular_JS_Autocomplete_In_MVC_With_Web_API_Output_.png"><img decoding="async" aria-describedby="caption-attachment-11394" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/Angular_JS_Autocomplete_In_MVC_With_Web_API_Output_.png" alt="Angular_JS_Autocomplete_In_MVC_With_Web_API_Output_" width="425" height="266" class="size-full wp-image-11394" srcset="/wp-content/uploads/2016/03/Angular_JS_Autocomplete_In_MVC_With_Web_API_Output_.png 425w, /wp-content/uploads/2016/03/Angular_JS_Autocomplete_In_MVC_With_Web_API_Output_-300x188.png 300w, /wp-content/uploads/2016/03/Angular_JS_Autocomplete_In_MVC_With_Web_API_Output_-400x250.png 400w" sizes="(max-width: 425px) 100vw, 425px" /></a><p id="caption-attachment-11394" class="wp-caption-text">Angular_JS_Autocomplete_In_MVC_With_Web_API_Output_</p></div></p>
<p><div id="attachment_11395" style="width: 437px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/Angular_JS_Autocomplete_In_MVC_With_Web_API_Output_With_Filter_.png"><img decoding="async" aria-describedby="caption-attachment-11395" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/Angular_JS_Autocomplete_In_MVC_With_Web_API_Output_With_Filter_.png" alt="Angular_JS_Autocomplete_In_MVC_With_Web_API_Output_With_Filter_" width="427" height="361" class="size-full wp-image-11395" srcset="/wp-content/uploads/2016/03/Angular_JS_Autocomplete_In_MVC_With_Web_API_Output_With_Filter_.png 427w, /wp-content/uploads/2016/03/Angular_JS_Autocomplete_In_MVC_With_Web_API_Output_With_Filter_-300x254.png 300w, /wp-content/uploads/2016/03/Angular_JS_Autocomplete_In_MVC_With_Web_API_Output_With_Filter_-400x338.png 400w" sizes="(max-width: 427px) 100vw, 427px" /></a><p id="caption-attachment-11395" class="wp-caption-text">Angular_JS_Autocomplete_In_MVC_With_Web_API_Output_With_Filter_</p></div></p>
<p>We have done everything!. That&#8217;s fantastic right? Have a happy coding.</p>
<p><em>Reference</em></p>
<li><a href="https://material.angularjs.org" target="_blank" rel="noopener">Angular JS Materials</a></li>
<p><strong>Conclusion</strong></p>
<p>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.</p>
<p><strong>Your turn. What do you think?</strong></p>
<p>A blog isn&#8217;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.</p>
<p>Kindest Regards<br />
Sibeesh Venu</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.sibeeshpassion.com/angular-js-autocomplete-in-mvc-with-web-api/feed/</wfw:commentRss>
			<slash:comments>4</slash:comments>
		
		
			</item>
		<item>
		<title>Chart Widgets With Server Side Data In MVC Using Angular JS And Web API</title>
		<link>https://www.sibeeshpassion.com/chart-widgets-with-server-side-data-in-mvc-using-angular-js-and-web-api/</link>
					<comments>https://www.sibeeshpassion.com/chart-widgets-with-server-side-data-in-mvc-using-angular-js-and-web-api/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Thu, 17 Mar 2016 05:33:35 +0000</pubDate>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Angular]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[Web API]]></category>
		<category><![CDATA[Angular JS]]></category>
		<category><![CDATA[Asp.Net]]></category>
		<category><![CDATA[Bar Chart]]></category>
		<category><![CDATA[Column Charts]]></category>
		<category><![CDATA[HighChart]]></category>
		<category><![CDATA[HighChart With Angular JS]]></category>
		<category><![CDATA[Line Chart]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[Pie Chart]]></category>
		<category><![CDATA[Scatter Chart]]></category>
		<category><![CDATA[Server Error in Application]]></category>
		<category><![CDATA[Spline Chart]]></category>
		<category><![CDATA[The resource cannot be found]]></category>
		<category><![CDATA[Widgets With Server Side Data]]></category>
		<guid isPermaLink="false">http://sibeecst_passion.com/?p=11359</guid>

					<description><![CDATA[In this article we will learn how we can create some client side chart widgets with the data from SQL Server database. We use MVC architecture with Web API and Angular JS to fetch the data and do all the manipulations. I am creating this application in Visual Studio 2015. In this project we covers topic of how to use HighChart with Angular JS. 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 Now we will go and create our application. [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>In this article we will learn how we can create some client side chart widgets with the data from <a href="http://sibeeshpassion.com/category/SQL/" target="_blank" rel="noopener">SQL </a>Server database. We use MVC architecture with Web API and Angular JS to fetch the data and do all the manipulations. I am creating this application in Visual Studio 2015. In this project we covers topic of how to use <a href="http://sibeeshpassion.com/category/products/HighChart/" target="_blank" rel="noopener">HighChart </a>with Angular JS. You can always get the tips/tricks/blogs about these mentioned technologies from the links given below. </p>
<li><a href="http://sibeeshpassion.com/category/angularjs/" target="_blank" rel="noopener">AngularJS Tips, Tricks, Blogs</a></li>
<li><a href="http://sibeeshpassion.com/category/mvc/" target="_blank" rel="noopener">MVC Tips, Tricks, Blogs</a></li>
<li><a href="http://sibeeshpassion.com/category/web-api/" target="_blank" rel="noopener">Web API Tips, Tricks, Blogs</a></li>
<p>Now we will go and create our application. I hope you will like this. </p>
<p><strong>Download the source code</strong></p>
<p>You can always download the source code here.</p>
<li><a href="https://code.msdn.microsoft.com/Chart-Widgets-With-Server-70f5cdac" target="_blank" rel="noopener">Widgets With Server Side Data</a></li>
<li><a href="http://sibeeshpassion.com/Download/MyDashboardSQLScript.rar" target="_blank" rel="noopener">SQL Scripts With Insert Queries</a></li>
<p><strong>Background</strong></p>
<p>I am working now in a personal dashboard application in which I uses HighChart products for the chart integration. We can always load the chart widgets with server side data and Angular JS right? Here we will discuss that. We are going to create the preceding charts for our dashboard. </p>
<li>Pie Chart</li>
<li>Spline Chart</li>
<li>Bar Chart</li>
<li>Line Chart</li>
<li>Scatter Chart</li>
<li>Column Chart</li>
<p>Once we are done, this is how our applications output will be. </p>
<p><div id="attachment_11360" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/Chart-Widgets-With-Server-Side-Data-In-MVC-Using-Angular-JS-And-Web-API-Output-e1458121833696.png"><img decoding="async" aria-describedby="caption-attachment-11360" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/Chart-Widgets-With-Server-Side-Data-In-MVC-Using-Angular-JS-And-Web-API-Output-1024x875.png" alt="Chart Widgets With Server Side Data In MVC Using Angular JS And Web API Output" width="634" height="542" class="size-large wp-image-11360" /></a><p id="caption-attachment-11360" class="wp-caption-text">Chart Widgets With Server Side Data In MVC Using Angular JS And Web API Output</p></div></p>
<p><strong>Create a MVC application</strong></p>
<p>Click File-> New-> Project then select MVC application. From the following pop up we will select the template as empty and select the core references and folders for MVC. </p>
<p><div id="attachment_11361" style="width: 660px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/MVC-Project-With-Empty-Template-e1458122053871.png"><img decoding="async" aria-describedby="caption-attachment-11361" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/MVC-Project-With-Empty-Template-e1458122053871.png" alt="MVC Project With Empty Template" width="650" height="508" class="size-full wp-image-11361" srcset="/wp-content/uploads/2016/03/MVC-Project-With-Empty-Template-e1458122053871.png 650w, /wp-content/uploads/2016/03/MVC-Project-With-Empty-Template-e1458122053871-300x234.png 300w, /wp-content/uploads/2016/03/MVC-Project-With-Empty-Template-e1458122053871-400x313.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><p id="caption-attachment-11361" class="wp-caption-text">MVC Project With Empty Template</p></div></p>
<p>Once you click OK, a project with MVC like folder structure with core references will be created for you.</p>
<p><div id="attachment_11362" style="width: 277px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/Folder-Structure-And-References-For-Empty-MVC-Project.png"><img decoding="async" aria-describedby="caption-attachment-11362" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/Folder-Structure-And-References-For-Empty-MVC-Project.png" alt="Folder Structure And References For Empty MVC Project" width="267" height="367" class="size-full wp-image-11362" srcset="/wp-content/uploads/2016/03/Folder-Structure-And-References-For-Empty-MVC-Project.png 267w, /wp-content/uploads/2016/03/Folder-Structure-And-References-For-Empty-MVC-Project-218x300.png 218w" sizes="(max-width: 267px) 100vw, 267px" /></a><p id="caption-attachment-11362" class="wp-caption-text">Folder Structure And References For Empty MVC Project</p></div></p>
<p>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. </p>
<li>Angular JS</li>
<li>jQuery</li>
<p>You can all the items mentioned above from NuGet. Right click on your project name and select Manage NuGet packages.</p>
<p><div id="attachment_11235" style="width: 660px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/02/Manage-NuGet-Package-Window-e1455700665396.png"><img decoding="async" aria-describedby="caption-attachment-11235" src="http://sibeeshpassion.com/wp-content/uploads/2016/02/Manage-NuGet-Package-Window-e1455700665396.png" alt="Manage NuGet Package Window" width="650" height="432" class="size-full wp-image-11235" srcset="/wp-content/uploads/2016/02/Manage-NuGet-Package-Window-e1455700665396.png 650w, /wp-content/uploads/2016/02/Manage-NuGet-Package-Window-e1455700665396-300x199.png 300w, /wp-content/uploads/2016/02/Manage-NuGet-Package-Window-e1455700665396-400x266.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><p id="caption-attachment-11235" class="wp-caption-text">Manage NuGet Package Window</p></div></p>
<p>Once you have installed those items, please make sure that all the items(jQuery, Angular JS files) are loaded in your scripts folder. </p>
<p><strong>Using the code</strong></p>
<p>As I have said before, we are going to use Angular JS for our client side operations, so it is better to create the Angular JS script files first right? Just to make sure that we have got all the required things :). For that, create a folder named <em>Widget</em> in script folder and right click -> Add -> New Item -> Select AngularJS Module and enter the module name -> Click Add.</p>
<p><div id="attachment_11363" style="width: 660px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/Creating-Angular-JS-Modue-In-MVC-Application-e1458122639235.png"><img decoding="async" aria-describedby="caption-attachment-11363" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/Creating-Angular-JS-Modue-In-MVC-Application-e1458122639235.png" alt="Creating Angular JS Modue In MVC Application" width="650" height="449" class="size-full wp-image-11363" srcset="/wp-content/uploads/2016/03/Creating-Angular-JS-Modue-In-MVC-Application-e1458122639235.png 650w, /wp-content/uploads/2016/03/Creating-Angular-JS-Modue-In-MVC-Application-e1458122639235-300x207.png 300w, /wp-content/uploads/2016/03/Creating-Angular-JS-Modue-In-MVC-Application-e1458122639235-160x110.png 160w, /wp-content/uploads/2016/03/Creating-Angular-JS-Modue-In-MVC-Application-e1458122639235-400x276.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><p id="caption-attachment-11363" class="wp-caption-text">Creating Angular JS Modue In MVC Application</p></div></p>
<p>Follow the same procedure to create Angular JS factory and Angular JS controller. Yes, we have set everything to get started our coding. Now we will create a Web API controller and get the data from database in JSON format. Let&#8217;s start then.</p>
<p><strong>Create Web API Controller</strong></p>
<p>To create a Web API controller, just right click on your controller folder and click Add -> Controller -> Select Web API controller &#8211; Empty ( We will create our own actions later) -> Name the controller (Here I am giving the controller name as Widget).</p>
<p>So our controller is ready, now we need to set up our database so that we can create Entity Model for our application later. </p>
<p><strong>Create a database</strong></p>
<p>The following query can be used to create a database in your SQL Server.</p>
<p>[sql]<br />
USE [master]<br />
GO</p>
<p>/****** Object:  Database [TrialsDB]    Script Date: 16-Mar-16 4:08:15 PM ******/<br />
CREATE DATABASE [TrialsDB]<br />
 CONTAINMENT = NONE<br />
 ON  PRIMARY<br />
( NAME = N&#8217;TrialsDB&#8217;, FILENAME = N&#8217;C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\TrialsDB.mdf&#8217; , SIZE = 3072KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )<br />
 LOG ON<br />
( NAME = N&#8217;TrialsDB_log&#8217;, FILENAME = N&#8217;C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\TrialsDB_log.ldf&#8217; , SIZE = 1024KB , MAXSIZE = 2048GB , FILEGROWTH = 10%)<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET COMPATIBILITY_LEVEL = 110<br />
GO</p>
<p>IF (1 = FULLTEXTSERVICEPROPERTY(&#8216;IsFullTextInstalled&#8217;))<br />
begin<br />
EXEC [TrialsDB].[dbo].[sp_fulltext_database] @action = &#8216;enable&#8217;<br />
end<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET ANSI_NULL_DEFAULT OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET ANSI_NULLS OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET ANSI_PADDING OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET ANSI_WARNINGS OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET ARITHABORT OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET AUTO_CLOSE OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET AUTO_CREATE_STATISTICS ON<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET AUTO_SHRINK OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET AUTO_UPDATE_STATISTICS ON<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET CURSOR_CLOSE_ON_COMMIT OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET CURSOR_DEFAULT  GLOBAL<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET CONCAT_NULL_YIELDS_NULL OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET NUMERIC_ROUNDABORT OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET QUOTED_IDENTIFIER OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET RECURSIVE_TRIGGERS OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET  DISABLE_BROKER<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET AUTO_UPDATE_STATISTICS_ASYNC OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET DATE_CORRELATION_OPTIMIZATION OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET TRUSTWORTHY OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET ALLOW_SNAPSHOT_ISOLATION OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET PARAMETERIZATION SIMPLE<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET READ_COMMITTED_SNAPSHOT OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET HONOR_BROKER_PRIORITY OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET RECOVERY FULL<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET  MULTI_USER<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET PAGE_VERIFY CHECKSUM<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET DB_CHAINING OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET FILESTREAM( NON_TRANSACTED_ACCESS = OFF )<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET TARGET_RECOVERY_TIME = 0 SECONDS<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET  READ_WRITE<br />
GO<br />
[/sql]</p>
<p>Now we will create the tables we needed. As of now I am going to create two tables. </p>
<li>SalesOrderDetail</li>
<li>Product</li>
<p>These tables are having relationship by the key <em>ProductID</em>.</p>
<p><strong>Create tables in database</strong></p>
<p>Below is the query to create SalesOrderDetail table in database.</p>
<p>[sql]<br />
USE [TrialsDB]<br />
GO</p>
<p>/****** Object:  Table [dbo].[SalesOrderDetail]    Script Date: 16-Mar-16 4:10:22 PM ******/<br />
SET ANSI_NULLS ON<br />
GO</p>
<p>SET QUOTED_IDENTIFIER ON<br />
GO</p>
<p>CREATE TABLE [dbo].[SalesOrderDetail](<br />
	[SalesOrderID] [int] NOT NULL,<br />
	[SalesOrderDetailID] [int] IDENTITY(1,1) NOT NULL,<br />
	[CarrierTrackingNumber] [nvarchar](25) NULL,<br />
	[OrderQty] [smallint] NOT NULL,<br />
	[ProductID] [int] NOT NULL,<br />
	[SpecialOfferID] [int] NOT NULL,<br />
	[UnitPrice] [money] NOT NULL,<br />
	[UnitPriceDiscount] [money] NOT NULL,<br />
	[LineTotal]  AS (isnull(([UnitPrice]*((1.0)-[UnitPriceDiscount]))*[OrderQty],(0.0))),<br />
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,<br />
	[ModifiedDate] [datetime] NOT NULL,<br />
 CONSTRAINT [PK_SalesOrderDetail_SalesOrderID_SalesOrderDetailID] PRIMARY KEY CLUSTERED<br />
(<br />
	[SalesOrderID] ASC,<br />
	[SalesOrderDetailID] ASC<br />
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]<br />
) ON [PRIMARY]</p>
<p>GO<br />
[/sql]</p>
<p>Now we will create the table Product.</p>
<p>[sql]<br />
USE [TrialsDB]<br />
GO</p>
<p>/****** Object:  Table [dbo].[Product]    Script Date: 16-Mar-16 4:11:29 PM ******/<br />
SET ANSI_NULLS ON<br />
GO</p>
<p>SET QUOTED_IDENTIFIER ON<br />
GO</p>
<p>CREATE TABLE [dbo].[Product](<br />
	[ProductID] [int] NOT NULL,<br />
	[Name] [nvarchar](max) NOT NULL,<br />
	[ProductNumber] [nvarchar](25) NOT NULL,<br />
	[MakeFlag] [bit] NOT NULL,<br />
	[FinishedGoodsFlag] [bit] NOT NULL,<br />
	[Color] [nvarchar](15) NULL,<br />
	[SafetyStockLevel] [smallint] NOT NULL,<br />
	[ReorderPoint] [smallint] NOT NULL,<br />
	[StandardCost] [money] NOT NULL,<br />
	[ListPrice] [money] NOT NULL,<br />
	[Size] [nvarchar](5) NULL,<br />
	[SizeUnitMeasureCode] [nchar](3) NULL,<br />
	[WeightUnitMeasureCode] [nchar](3) NULL,<br />
	[Weight] [decimal](8, 2) NULL,<br />
	[DaysToManufacture] [int] NOT NULL,<br />
	[ProductLine] [nchar](2) NULL,<br />
	[Class] [nchar](2) NULL,<br />
	[Style] [nchar](2) NULL,<br />
	[ProductSubcategoryID] [int] NULL,<br />
	[ProductModelID] [int] NULL,<br />
	[SellStartDate] [datetime] NOT NULL,<br />
	[SellEndDate] [datetime] NULL,<br />
	[DiscontinuedDate] [datetime] NULL,<br />
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,<br />
	[ModifiedDate] [datetime] NOT NULL<br />
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]</p>
<p>GO<br />
[/sql]</p>
<p>Can we insert some data to the tables now?</p>
<p><strong>Insert data to table</strong></p>
<p>You can use the below query to insert the data to SalesOrderDetail.</p>
<p>[sql]<br />
USE [TrialsDB]<br />
GO</p>
<p>INSERT INTO [dbo].[SalesOrderDetail]<br />
           ([SalesOrderID]<br />
           ,[CarrierTrackingNumber]<br />
           ,[OrderQty]<br />
           ,[ProductID]<br />
           ,[SpecialOfferID]<br />
           ,[UnitPrice]<br />
           ,[UnitPriceDiscount]<br />
           ,[rowguid]<br />
           ,[ModifiedDate])<br />
     VALUES<br />
           (&lt;SalesOrderID, int,&gt;<br />
           ,&lt;CarrierTrackingNumber, nvarchar(25),&gt;<br />
           ,&lt;OrderQty, smallint,&gt;<br />
           ,&lt;ProductID, int,&gt;<br />
           ,&lt;SpecialOfferID, int,&gt;<br />
           ,&lt;UnitPrice, money,&gt;<br />
           ,&lt;UnitPriceDiscount, money,&gt;<br />
           ,&lt;rowguid, uniqueidentifier,&gt;<br />
           ,&lt;ModifiedDate, datetime,&gt;)<br />
GO<br />
[/sql]</p>
<p>and the following query can be used for the table <em>Product</em></p>
<p>[sql]<br />
USE [TrialsDB]<br />
GO</p>
<p>INSERT INTO [dbo].[Product]<br />
           ([ProductID]<br />
           ,[Name]<br />
           ,[ProductNumber]<br />
           ,[MakeFlag]<br />
           ,[FinishedGoodsFlag]<br />
           ,[Color]<br />
           ,[SafetyStockLevel]<br />
           ,[ReorderPoint]<br />
           ,[StandardCost]<br />
           ,[ListPrice]<br />
           ,[Size]<br />
           ,[SizeUnitMeasureCode]<br />
           ,[WeightUnitMeasureCode]<br />
           ,[Weight]<br />
           ,[DaysToManufacture]<br />
           ,[ProductLine]<br />
           ,[Class]<br />
           ,[Style]<br />
           ,[ProductSubcategoryID]<br />
           ,[ProductModelID]<br />
           ,[SellStartDate]<br />
           ,[SellEndDate]<br />
           ,[DiscontinuedDate]<br />
           ,[rowguid]<br />
           ,[ModifiedDate])<br />
     VALUES<br />
           (&lt;ProductID, int,&gt;<br />
           ,&lt;Name, nvarchar(max),&gt;<br />
           ,&lt;ProductNumber, nvarchar(25),&gt;<br />
           ,&lt;MakeFlag, bit,&gt;<br />
           ,&lt;FinishedGoodsFlag, bit,&gt;<br />
           ,&lt;Color, nvarchar(15),&gt;<br />
           ,&lt;SafetyStockLevel, smallint,&gt;<br />
           ,&lt;ReorderPoint, smallint,&gt;<br />
           ,&lt;StandardCost, money,&gt;<br />
           ,&lt;ListPrice, money,&gt;<br />
           ,&lt;Size, nvarchar(5),&gt;<br />
           ,&lt;SizeUnitMeasureCode, nchar(3),&gt;<br />
           ,&lt;WeightUnitMeasureCode, nchar(3),&gt;<br />
           ,&lt;Weight, decimal(8,2),&gt;<br />
           ,&lt;DaysToManufacture, int,&gt;<br />
           ,&lt;ProductLine, nchar(2),&gt;<br />
           ,&lt;Class, nchar(2),&gt;<br />
           ,&lt;Style, nchar(2),&gt;<br />
           ,&lt;ProductSubcategoryID, int,&gt;<br />
           ,&lt;ProductModelID, int,&gt;<br />
           ,&lt;SellStartDate, datetime,&gt;<br />
           ,&lt;SellEndDate, datetime,&gt;<br />
           ,&lt;DiscontinuedDate, datetime,&gt;<br />
           ,&lt;rowguid, uniqueidentifier,&gt;<br />
           ,&lt;ModifiedDate, datetime,&gt;)<br />
GO<br />
[/sql] </p>
<p>So let us say, we have inserted the data as follows. If you feel bored of inserting data manually, you can always tun the SQL script file attached which has the insertion queries. Just run that, you will be all OK. If you don&#8217;t know how to generate SQL scripts with data, I strongly recommend you to have a read <a href="http://sibeeshpassion.com/generate-database-scripts-with-data-in-sql-server/" target="_blank" rel="noopener">here</a></p>
<p>Next thing we are going to do is creating a ADO.NET Entity Data Model. </p>
<p><strong>Create Entity Data Model</strong></p>
<p>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. Here I gave <em>Dashboard</em> for our Entity data model name. Now you can see a file with edmx extension have been created. If you open that file, you can see as below. </p>
<p><div id="attachment_11364" style="width: 513px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/Entity-Data-Model.png"><img decoding="async" aria-describedby="caption-attachment-11364" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/Entity-Data-Model.png" alt="Entity Data Model" width="503" height="669" class="size-full wp-image-11364" srcset="/wp-content/uploads/2016/03/Entity-Data-Model.png 503w, /wp-content/uploads/2016/03/Entity-Data-Model-226x300.png 226w, /wp-content/uploads/2016/03/Entity-Data-Model-400x532.png 400w, /wp-content/uploads/2016/03/Entity-Data-Model-451x600.png 451w" sizes="(max-width: 503px) 100vw, 503px" /></a><p id="caption-attachment-11364" class="wp-caption-text">Entity Data Model</p></div></p>
<p>Now go back our Web API controller. Please change the code as below.</p>
<p>[csharp]<br />
using System;<br />
using System.Collections.Generic;<br />
using System.Linq;<br />
using System.Net;<br />
using System.Net.Http;<br />
using System.Web.Http;<br />
using MyDashboard.Models;<br />
using Newtonsoft.Json;<br />
namespace MyDashboard.Controllers<br />
{<br />
    public class WidgetController : ApiController<br />
    {<br />
        public DashboardEntities de = new DashboardEntities();<br />
        Retriever ret = new Retriever();<br />
        public string getWidgetData()<br />
        {<br />
            var dataList = ret.GetWidgetData(de);<br />
            return dataList;<br />
        }<br />
    }<br />
}<br />
[/csharp]</p>
<p>Here we have created a new model class <em>Retriever </em> and we have added a method <em>GetWidgetData</em> in that class. Now let us see what I have coded in that.</p>
<p>[csharp]<br />
using Newtonsoft.Json;<br />
using System;<br />
using System.Collections.Generic;<br />
using System.Linq;<br />
using System.Web;</p>
<p>namespace MyDashboard.Models<br />
{<br />
    public class Retriever<br />
    {<br />
        public string GetWidgetData(DashboardEntities de)<br />
        {<br />
            try<br />
            {<br />
                using (de)<br />
                {<br />
                    var resList = (from sales in de.SalesOrderDetails<br />
                                  join prod in de.Products<br />
                                  on sales.ProductID equals prod.ProductID<br />
                                  select new<br />
                                  {<br />
                                      ProductName = prod.Name,<br />
                                      QuantityOrdered = sales.OrderQty<br />
                                  });<br />
                    var res = resList.GroupBy(d =&gt; d.ProductName).Select(g =&gt; new<br />
                    {<br />
                        name = g.FirstOrDefault().ProductName,<br />
                        y = g.Sum(s =&gt; s.QuantityOrdered)<br />
                    });<br />
                    return JsonConvert.SerializeObject(res, Formatting.None, new JsonSerializerSettings()<br />
                    {<br />
                        ReferenceLoopHandling = ReferenceLoopHandling.Ignore<br />
                    });<br />
                }<br />
            }<br />
            catch (Exception)<br />
            {<br />
                throw new NotImplementedException();<br />
            }</p>
<p>        }<br />
    }<br />
}<br />
[/csharp]</p>
<p>Here we are using LINQ to fetch the data, We uses JOIN in the query to find the <em>Name </em> from the table Products. Once the data is ready, we are just do group by the column <em>ProductName</em> and sum of <em>QuantityOrdered</em>. </p>
<p>[csharp]<br />
var res = resList.GroupBy(d =&gt; d.ProductName).Select(g =&gt; new<br />
                    {<br />
                        name = g.FirstOrDefault().ProductName,<br />
                        y = g.Sum(s =&gt; s.QuantityOrdered)<br />
                    });<br />
[/csharp]</p>
<p>So the coding part to fetch the data from database is read, now we need to check whether our Web API is ready for action!. To check that, you just need to run the URL <em>http://localhost:1646/Api/Widget</em>. Here <em>Widget</em> is our Web API controller name. I hope you get the data as a result. If you are getting the error <em>Server Error in &#8216;/&#8217; Application The resource cannot be found</em>, you need to configure your Web API in <em>Global.asax.cs</em>. You got this error just because you created an Empty project with only needed references. So here we need to do his step by our own. No worries, we will do it now. Just change the <em>Global.asax.cs </em>as follows. </p>
<p>[csharp]<br />
using System;<br />
using System.Collections.Generic;<br />
using System.Linq;<br />
using System.Web;<br />
using System.Web.Http;<br />
using System.Web.Mvc;<br />
using System.Web.Routing;</p>
<p>namespace MyDashboard<br />
{<br />
    public class MvcApplication : System.Web.HttpApplication<br />
    {<br />
        protected void Application_Start()<br />
        {<br />
            AreaRegistration.RegisterAllAreas();<br />
            GlobalConfiguration.Configure(WebApiConfig.Register);//This is for setting the configuration<br />
            RouteConfig.RegisterRoutes(RouteTable.Routes);<br />
        }<br />
    }<br />
}<br />
[/csharp]</p>
<p>Now build your application and run the same URL again, you will get the output as follows. </p>
<p><div id="attachment_11365" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/Web-API-Output.png"><img decoding="async" aria-describedby="caption-attachment-11365" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/Web-API-Output-1024x258.png" alt="Web API Output" width="634" height="160" class="size-large wp-image-11365" srcset="/wp-content/uploads/2016/03/Web-API-Output-1024x258.png 1024w, /wp-content/uploads/2016/03/Web-API-Output-300x75.png 300w, /wp-content/uploads/2016/03/Web-API-Output-768x193.png 768w, /wp-content/uploads/2016/03/Web-API-Output-400x101.png 400w, /wp-content/uploads/2016/03/Web-API-Output.png 1367w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-11365" class="wp-caption-text">Web API Output</p></div></p>
<p>Now we will go back to our angular JS files and consume this Web API. You need to change the scripts in the <em>app.js, controller.js, factory.js</em> as follows.</p>
<p><strong>app.js</strong></p>
<p>[js]<br />
(function () {<br />
    &#8216;use strict&#8217;;<br />
    angular.module(&#8216;WidgetsApp&#8217;, []);<br />
})();<br />
[/js]</p>
<p><strong>controller.js</strong></p>
<p>[js]<br />
(function () {<br />
    &#8216;use strict&#8217;;<br />
    angular<br />
        .module(&#8216;WidgetsApp&#8217;)<br />
        .controller(&#8216;WidgetsController&#8217;, function ($scope, factory) {<br />
            var res = factory.getData();<br />
            var options;<br />
            if (res != undefined) {<br />
                res.then(function (d) {<br />
                    var data = JSON.parse(d.data);</p>
<p>                }, function (error) {<br />
                    console.log(&#8216;Oops! Something went wrong while fetching the data.&#8217;);<br />
                });<br />
            }<br />
        });<br />
})();</p>
<p>[/js]</p>
<p>Once our service is called, we will get the data in return. We will parse the same and store it in a variable for future use.</p>
<p>[js]<br />
var data = JSON.parse(d.data);<br />
[/js]</p>
<p><strong>factory.js</strong></p>
<p>[js]<br />
(function () {<br />
    &#8216;use strict&#8217;;<br />
    angular<br />
        .module(&#8216;WidgetsApp&#8217;)<br />
        .service(&#8216;factory&#8217;, function ($http) {<br />
            this.getData = function () {<br />
                var url = &#8216;Api/Widget&#8217;;<br />
                return $http({<br />
                    type: &#8216;get&#8217;,<br />
                    url: url<br />
                });<br />
            }<br />
        });<br />
})();<br />
[/js]</p>
<p>AS you can see we are just calling our Web API <em>Api/Widget</em> with the help of <a href="http://sibeeshpassion.com/learning-angularjs-http/" target="_blank" rel="noopener">Angular $http.</a></p>
<p>Now we a view to show our data right? Yes, we need a controller too!.</p>
<p><strong>Create a MVC controller</strong></p>
<p>To create a controller, we need to right click on the controller folder, Add &#8211; Controller. I hope you will be given a controller as follows. </p>
<p>[csharp]<br />
using System;<br />
using System.Collections.Generic;<br />
using System.Linq;<br />
using System.Web;<br />
using System.Web.Mvc;</p>
<p>namespace MyDashboard.Controllers<br />
{<br />
    public class HomeController : Controller<br />
    {<br />
        // GET: Home<br />
        public ActionResult Index()<br />
        {<br />
            return View();<br />
        }<br />
    }<br />
}<br />
[/csharp]</p>
<p>Here <em>Home</em> is our controller name. </p>
<p>Now we need a view right?</p>
<p><strong>Creating a view</strong></p>
<p>To create a view, just right click on your controller name -> Add View -> Add.</p>
<p><div id="attachment_11366" style="width: 635px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/Creating-a-view.png"><img decoding="async" aria-describedby="caption-attachment-11366" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/Creating-a-view.png" alt="Creating a view" width="625" height="398" class="size-full wp-image-11366" srcset="/wp-content/uploads/2016/03/Creating-a-view.png 625w, /wp-content/uploads/2016/03/Creating-a-view-300x191.png 300w, /wp-content/uploads/2016/03/Creating-a-view-400x255.png 400w" sizes="(max-width: 625px) 100vw, 625px" /></a><p id="caption-attachment-11366" class="wp-caption-text">Creating a view</p></div></p>
<p>Now in your view add the needed references.</p>
<p>[html]<br />
&lt;script src=&quot;~/scripts/jquery-1.10.2.min.js&quot;&gt;&lt;/script&gt;<br />
&lt;script src=&quot;~/scripts/jquery-ui-1.11.4.min.js&quot;&gt;&lt;/script&gt;<br />
&lt;script src=&quot;~/scripts/angular.min.js&quot;&gt;&lt;/script&gt;<br />
&lt;script src=&quot;~/scripts/angular-aria.js&quot;&gt;&lt;/script&gt;<br />
&lt;script src=&quot;~/scripts/angular-route.js&quot;&gt;&lt;/script&gt;<br />
&lt;script src=&quot;~/scripts/Widgets/app.js&quot;&gt;&lt;/script&gt;<br />
&lt;script src=&quot;~/scripts/Widgets/controller.js&quot;&gt;&lt;/script&gt;<br />
&lt;script src=&quot;~/scripts/Widgets/factory.js&quot;&gt;&lt;/script&gt;<br />
[/html]</p>
<p>Once we add the references, we can call our Angular JS controller as follows.</p>
<p>[html]<br />
&lt;div ng-app=&quot;WidgetsApp&quot;&gt;<br />
    &lt;div ng-controller=&quot;WidgetsController&quot;&gt;<br />
    &lt;/div&gt;<br />
&lt;/div&gt;<br />
[/html]</p>
<p>Now if you run your application, you can see our Web API call works fine and successfully get the data. Next thing we need to do is creating charts with the data we get.</p>
<p><strong>Create chart widgets with the data</strong></p>
<p>As I said, we are going to to create HighChart chart widgets, we need to add a reference to use that plug in.</p>
<p>[html]<br />
&lt;script src=&quot;https://code.highcharts.com/highcharts.js&quot;&gt;&lt;/script&gt;<br />
[/html]</p>
<p>Now create elements where we can load our chart.</p>
<p>[html]<br />
&lt;div ng-app=&quot;WidgetsApp&quot;&gt;<br />
    &lt;div ng-controller=&quot;WidgetsController&quot;&gt;<br />
        &lt;div id=&quot;widgetPie&quot; class=&quot;widget&quot;&gt;Placeholder for chart&lt;/div&gt;<br />
        &lt;div id=&quot;widgetspline&quot; class=&quot;widget&quot;&gt;Placeholder for chart&lt;/div&gt;<br />
        &lt;div id=&quot;widgetBar&quot; class=&quot;widget&quot;&gt;Placeholder for chart&lt;/div&gt;<br />
        &lt;div id=&quot;widgetLine&quot; class=&quot;widget&quot;&gt;Placeholder for chart&lt;/div&gt;<br />
        &lt;div id=&quot;widgetScatter&quot; class=&quot;widget&quot;&gt;Placeholder for chart&lt;/div&gt;<br />
        &lt;div id=&quot;widgetColumn&quot; class=&quot;widget&quot;&gt;Placeholder for chart&lt;/div&gt;<br />
    &lt;/div&gt;<br />
&lt;/div&gt;<br />
[/html]</p>
<p>You can style your elements as follows if you want, but this is optional.</p>
<p>[css]<br />
&lt;style&gt;<br />
    .widget {<br />
        width: 30%;<br />
        border: 1px solid #ccc;<br />
        padding: 10px;<br />
        margin: 5px;<br />
        border-radius: 3px;<br />
        transition: none;<br />
        -webkit-transition: none;<br />
        -moz-transition: none;<br />
        -o-transition: none;<br />
        cursor: move;<br />
        display: inline-block;<br />
        float:left;<br />
    }<br />
&lt;/style&gt;<br />
[/css]</p>
<p>Go back to our Angular JS controller and add the below codes right after we get the data from server. </p>
<p><strong>Pie Chart</strong></p>
<p>[js]<br />
var data = JSON.parse(d.data);<br />
                    var categories = [];<br />
                    for (var i = 0; i &lt; data.length; i++) {<br />
                        categories.push(data[i].name)<br />
                    }<br />
                    options = new Highcharts.chart(&#8216;widgetPie&#8217;, {<br />
                        credits: {<br />
                            enabled: false<br />
                        },<br />
                        chart: {<br />
                            type: &#8216;pie&#8217;,<br />
                            renderTo: &#8221;<br />
                        },<br />
                        title: {<br />
                            text: &#8216;Product VS Quantity &#8211; Pie Chart&#8217;<br />
                        },<br />
                        plotOptions: {<br />
                            pie: {<br />
                                allowPointSelect: true,<br />
                                cursor: &#8216;pointer&#8217;,<br />
                                dataLabels: {<br />
                                    enabled: false,<br />
                                    format: &#8216;&lt;b&gt;{point.name}&lt;/b&gt;: {point.y:,.0f}&#8217;<br />
                                }<br />
                            }<br />
                        },<br />
                        series: [{<br />
                            name:&#8217;Quantity&#8217;,<br />
                            data: data<br />
                        }]<br />
                    });<br />
[/js]</p>
<p>Now run your application, you can see a pie chart with the data given. </p>
<p><div id="attachment_11368" style="width: 358px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/Pie-Chart-In-MVC-With-Angular-JS-And-Web-API.png"><img decoding="async" aria-describedby="caption-attachment-11368" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/Pie-Chart-In-MVC-With-Angular-JS-And-Web-API.png" alt="Pie Chart In MVC With Angular JS And Web API" width="348" height="427" class="size-full wp-image-11368" srcset="/wp-content/uploads/2016/03/Pie-Chart-In-MVC-With-Angular-JS-And-Web-API.png 348w, /wp-content/uploads/2016/03/Pie-Chart-In-MVC-With-Angular-JS-And-Web-API-244x300.png 244w" sizes="(max-width: 348px) 100vw, 348px" /></a><p id="caption-attachment-11368" class="wp-caption-text">Pie Chart In MVC With Angular JS And Web API</p></div> </p>
<p><strong>Column Chart</strong></p>
<p>[js]<br />
options = new Highcharts.chart(&#8216;widgetColumn&#8217;, {<br />
                        credits: {<br />
                            enabled: false<br />
                        },<br />
                        chart: {<br />
                            type: &#8216;column&#8217;,<br />
                            renderTo: &#8221;<br />
                        },<br />
                        title: {<br />
                            text: &#8216;Product VS Quantity &#8211; Column Chart&#8217;<br />
                        },<br />
                        series: [{<br />
                            name: &#8216;Quantity&#8217;,<br />
                            data: data<br />
                        }]<br />
                    });<br />
[/js]</p>
<p>Now run your application, you can see a column chart with the data given. </p>
<p><div id="attachment_11369" style="width: 364px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/Column-Chart-In-MVC-With-Angular-JS-And-Web-API.png"><img decoding="async" aria-describedby="caption-attachment-11369" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/Column-Chart-In-MVC-With-Angular-JS-And-Web-API.png" alt="Column Chart In MVC With Angular JS And Web API" width="354" height="433" class="size-full wp-image-11369" srcset="/wp-content/uploads/2016/03/Column-Chart-In-MVC-With-Angular-JS-And-Web-API.png 354w, /wp-content/uploads/2016/03/Column-Chart-In-MVC-With-Angular-JS-And-Web-API-245x300.png 245w" sizes="(max-width: 354px) 100vw, 354px" /></a><p id="caption-attachment-11369" class="wp-caption-text">Column Chart In MVC With Angular JS And Web API</p></div></p>
<p><strong>Bar Chart</strong></p>
<p>[js]<br />
options = new Highcharts.chart(&#8216;widgetBar&#8217;, {<br />
                        credits: {<br />
                            enabled: false<br />
                        },<br />
                        chart: {<br />
                            type: &#8216;bar&#8217;,<br />
                            renderTo: &#8221;<br />
                        },<br />
                        title: {<br />
                            text: &#8216;Product VS Quantity &#8211; Bar Chart&#8217;<br />
                        },<br />
                        series: [{<br />
                            name: &#8216;Quantity&#8217;,<br />
                            data: data<br />
                        }]<br />
                    });<br />
[/js]</p>
<p>Now run your application, you can see a Bar chart with the data given. </p>
<p><div id="attachment_11370" style="width: 362px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/Bar-Chart-In-MVC-With-Angular-JS-And-Web-API.png"><img decoding="async" aria-describedby="caption-attachment-11370" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/Bar-Chart-In-MVC-With-Angular-JS-And-Web-API.png" alt="Bar Chart In MVC With Angular JS And Web API" width="352" height="431" class="size-full wp-image-11370" srcset="/wp-content/uploads/2016/03/Bar-Chart-In-MVC-With-Angular-JS-And-Web-API.png 352w, /wp-content/uploads/2016/03/Bar-Chart-In-MVC-With-Angular-JS-And-Web-API-245x300.png 245w" sizes="(max-width: 352px) 100vw, 352px" /></a><p id="caption-attachment-11370" class="wp-caption-text">Bar Chart In MVC With Angular JS And Web API</p></div></p>
<p><strong>Line Chart</strong></p>
<p>[js]<br />
options = new Highcharts.chart(&#8216;widgetLine&#8217;, {<br />
                        credits: {<br />
                            enabled: false<br />
                        },<br />
                        chart: {<br />
                            type: &#8216;line&#8217;,<br />
                            renderTo: &#8221;<br />
                        },<br />
                        title: {<br />
                            text: &#8216;Product VS Quantity &#8211; Line Chart&#8217;<br />
                        },<br />
                        series: [{<br />
                            name: &#8216;Quantity&#8217;,<br />
                            data: data<br />
                        }]<br />
                    });<br />
[/js]</p>
<p>Now run your application, you can see a Line chart with the data given. </p>
<p><div id="attachment_11371" style="width: 364px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/Line-Chart-In-MVC-With-Angular-JS-And-Web-API.png"><img decoding="async" aria-describedby="caption-attachment-11371" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/Line-Chart-In-MVC-With-Angular-JS-And-Web-API.png" alt="Line Chart In MVC With Angular JS And Web API" width="354" height="436" class="size-full wp-image-11371" srcset="/wp-content/uploads/2016/03/Line-Chart-In-MVC-With-Angular-JS-And-Web-API.png 354w, /wp-content/uploads/2016/03/Line-Chart-In-MVC-With-Angular-JS-And-Web-API-244x300.png 244w" sizes="(max-width: 354px) 100vw, 354px" /></a><p id="caption-attachment-11371" class="wp-caption-text">Line Chart In MVC With Angular JS And Web API</p></div></p>
<p><strong>Spline Chart</strong></p>
<p>[js]<br />
options = new Highcharts.chart(&#8216;widgetspline&#8217;, {<br />
                        credits: {<br />
                            enabled: false<br />
                        },<br />
                        chart: {<br />
                            type: &#8216;spline&#8217;,<br />
                            renderTo: &#8221;<br />
                        },<br />
                        title: {<br />
                            text: &#8216;Product VS Quantity &#8211; Spline Chart&#8217;<br />
                        },<br />
                        series: [{<br />
                            name: &#8216;Quantity&#8217;,<br />
                            data: data<br />
                        }]<br />
                    });<br />
[/js]</p>
<p>Now run your application, you can see a Spline chart with the data given. </p>
<p><div id="attachment_11372" style="width: 363px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/Spline-Chart-In-MVC-With-Angular-JS-And-Web-API.png"><img decoding="async" aria-describedby="caption-attachment-11372" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/Spline-Chart-In-MVC-With-Angular-JS-And-Web-API.png" alt="Spline Chart In MVC With Angular JS And Web API" width="353" height="432" class="size-full wp-image-11372" srcset="/wp-content/uploads/2016/03/Spline-Chart-In-MVC-With-Angular-JS-And-Web-API.png 353w, /wp-content/uploads/2016/03/Spline-Chart-In-MVC-With-Angular-JS-And-Web-API-245x300.png 245w" sizes="(max-width: 353px) 100vw, 353px" /></a><p id="caption-attachment-11372" class="wp-caption-text">Spline Chart In MVC With Angular JS And Web API</p></div></p>
<p><strong>Scatter Chart</strong></p>
<p>[js]<br />
 options = new Highcharts.chart(&#8216;widgetScatter&#8217;, {<br />
                        credits: {<br />
                            enabled: false<br />
                        },<br />
                        chart: {<br />
                            type: &#8216;scatter&#8217;,<br />
                            renderTo: &#8221;<br />
                        },<br />
                        title: {<br />
                            text: &#8216;Product VS Quantity &#8211; Scatter Chart&#8217;<br />
                        },<br />
                        series: [{<br />
                            name: &#8216;Quantity&#8217;,<br />
                            data: data<br />
                        }]<br />
                    });<br />
[/js]</p>
<p>Now run your application, you can see a Scatter chart with the data given. </p>
<p><div id="attachment_11374" style="width: 361px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/Scatter-Chart-In-MVC-With-Angular-JS-And-Web-API.png"><img decoding="async" aria-describedby="caption-attachment-11374" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/Scatter-Chart-In-MVC-With-Angular-JS-And-Web-API.png" alt="Scatter Chart In MVC With Angular JS And Web API" width="351" height="432" class="size-full wp-image-11374" srcset="/wp-content/uploads/2016/03/Scatter-Chart-In-MVC-With-Angular-JS-And-Web-API.png 351w, /wp-content/uploads/2016/03/Scatter-Chart-In-MVC-With-Angular-JS-And-Web-API-244x300.png 244w" sizes="(max-width: 351px) 100vw, 351px" /></a><p id="caption-attachment-11374" class="wp-caption-text">Scatter Chart In MVC With Angular JS And Web API</p></div></p>
<p>Now this is how complete code for our controller.js file looks like. </p>
<p>[js]<br />
(function () {<br />
    &#8216;use strict&#8217;;<br />
    angular<br />
        .module(&#8216;WidgetsApp&#8217;)<br />
        .controller(&#8216;WidgetsController&#8217;, function ($scope, factory) {<br />
            var res = factory.getData();<br />
            var options;<br />
            if (res != undefined) {<br />
                res.then(function (d) {<br />
                    var data = JSON.parse(d.data);<br />
                    var categories = [];<br />
                    for (var i = 0; i &lt; data.length; i++) {<br />
                        categories.push(data[i].name)<br />
                    }<br />
                    options = new Highcharts.chart(&#8216;widgetPie&#8217;, {<br />
                        credits: {<br />
                            enabled: false<br />
                        },<br />
                        chart: {<br />
                            type: &#8216;pie&#8217;,<br />
                            renderTo: &#8221;<br />
                        },<br />
                        title: {<br />
                            text: &#8216;Product VS Quantity &#8211; Pie Chart&#8217;<br />
                        },<br />
                        plotOptions: {<br />
                            pie: {<br />
                                allowPointSelect: true,<br />
                                cursor: &#8216;pointer&#8217;,<br />
                                dataLabels: {<br />
                                    enabled: false,<br />
                                    format: &#8216;&lt;b&gt;{point.name}&lt;/b&gt;: {point.y:,.0f}&#8217;<br />
                                }<br />
                            }<br />
                        },<br />
                        series: [{<br />
                            name:&#8217;Quantity&#8217;,<br />
                            data: data<br />
                        }]<br />
                    });<br />
                    options = new Highcharts.chart(&#8216;widgetColumn&#8217;, {<br />
                        credits: {<br />
                            enabled: false<br />
                        },<br />
                        chart: {<br />
                            type: &#8216;column&#8217;,<br />
                            renderTo: &#8221;<br />
                        },<br />
                        title: {<br />
                            text: &#8216;Product VS Quantity &#8211; Column Chart&#8217;<br />
                        },<br />
                        series: [{<br />
                            name: &#8216;Quantity&#8217;,<br />
                            data: data<br />
                        }]<br />
                    });<br />
                    options = new Highcharts.chart(&#8216;widgetBar&#8217;, {<br />
                        credits: {<br />
                            enabled: false<br />
                        },<br />
                        chart: {<br />
                            type: &#8216;bar&#8217;,<br />
                            renderTo: &#8221;<br />
                        },<br />
                        title: {<br />
                            text: &#8216;Product VS Quantity &#8211; Bar Chart&#8217;<br />
                        },<br />
                        series: [{<br />
                            name: &#8216;Quantity&#8217;,<br />
                            data: data<br />
                        }]<br />
                    });<br />
                    options = new Highcharts.chart(&#8216;widgetLine&#8217;, {<br />
                        credits: {<br />
                            enabled: false<br />
                        },<br />
                        chart: {<br />
                            type: &#8216;line&#8217;,<br />
                            renderTo: &#8221;<br />
                        },<br />
                        title: {<br />
                            text: &#8216;Product VS Quantity &#8211; Line Chart&#8217;<br />
                        },<br />
                        series: [{<br />
                            name: &#8216;Quantity&#8217;,<br />
                            data: data<br />
                        }]<br />
                    });<br />
                    options = new Highcharts.chart(&#8216;widgetspline&#8217;, {<br />
                        credits: {<br />
                            enabled: false<br />
                        },<br />
                        chart: {<br />
                            type: &#8216;spline&#8217;,<br />
                            renderTo: &#8221;<br />
                        },<br />
                        title: {<br />
                            text: &#8216;Product VS Quantity &#8211; Spline Chart&#8217;<br />
                        },<br />
                        series: [{<br />
                            name: &#8216;Quantity&#8217;,<br />
                            data: data<br />
                        }]<br />
                    });<br />
                    options = new Highcharts.chart(&#8216;widgetScatter&#8217;, {<br />
                        credits: {<br />
                            enabled: false<br />
                        },<br />
                        chart: {<br />
                            type: &#8216;scatter&#8217;,<br />
                            renderTo: &#8221;<br />
                        },<br />
                        title: {<br />
                            text: &#8216;Product VS Quantity &#8211; Scatter Chart&#8217;<br />
                        },<br />
                        series: [{<br />
                            name: &#8216;Quantity&#8217;,<br />
                            data: data<br />
                        }]<br />
                    });<br />
                }, function (error) {<br />
                    console.log(&#8216;Oops! Something went wrong while fetching the data.&#8217;);<br />
                });<br />
            }<br />
        });<br />
})();<br />
[/js]</p>
<p>If you have configured all the chart types, we can see the output now 🙂</p>
<p><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/Chart-Widgets-In-MVC-With-Angular-JS-And-Web-API-e1458191984345.png"><img decoding="async" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/Chart-Widgets-In-MVC-With-Angular-JS-And-Web-API-1024x907.png" alt="Chart Widgets In MVC With Angular JS And Web API" width="634" height="562" class="alignnone size-large wp-image-11375" /></a></p>
<p>We have done everything!. That&#8217;s fantastic right? Have a happy coding.</p>
<p><strong>Conclusion</strong></p>
<p>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.</p>
<p><strong>Your turn. What do you think?</strong></p>
<p>A blog isn&#8217;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.</p>
<p>Kindest Regards<br />
Sibeesh Venu</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.sibeeshpassion.com/chart-widgets-with-server-side-data-in-mvc-using-angular-js-and-web-api/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Fix To No Access-Control-Allow-Origin header is present Or Working With Cross Origin Request In Asp Net Web API</title>
		<link>https://www.sibeeshpassion.com/fix-to-no-access-control-allow-origin-header-is-present-or-working-with-cross-origin-request-in-asp-net-web-api/</link>
					<comments>https://www.sibeeshpassion.com/fix-to-no-access-control-allow-origin-header-is-present-or-working-with-cross-origin-request-in-asp-net-web-api/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Fri, 11 Mar 2016 09:28:29 +0000</pubDate>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Web API]]></category>
		<category><![CDATA[Configure Web API In IIS]]></category>
		<category><![CDATA[CORS]]></category>
		<category><![CDATA[Cross Origin Request In Asp Net Web API]]></category>
		<category><![CDATA[IIS]]></category>
		<category><![CDATA[No Access-Control-Allow-Origin]]></category>
		<guid isPermaLink="false">http://sibeecst_passion.com/?p=11345</guid>

					<description><![CDATA[[toc] Introduction In this article we are going to few possible fixes we can apply when we get an error &#8220;Response to the preflight request doesn&#8217;t pass access control check: No &#8216;Access-Control-Allow-Origin&#8217; header is present on the requested resource. Origin &#8216;http://localhost:58018&#8217; is therefore not allowed access&#8221;. We get this error when we are trying to get some data from another origin may be via an AJAX call. In this post, we will discuss the solutions for this error in detail and we will also discuss Cross Origin Requests. Here I am going to use Visual Studio 2015, Web API 2. [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>[toc]</p>
<h2>Introduction</h2>
<p>In this article we are going to few possible fixes we can apply when we get an error &#8220;Response to the preflight request doesn&#8217;t pass access control check: No &#8216;Access-Control-Allow-Origin&#8217; header is present on the requested resource. Origin &#8216;http://localhost:58018&#8217; is therefore not allowed access&#8221;. We get this error when we are trying to get some data from another origin may be via an <a href="http://sibeeshpassion.com/tag/ajax/" target="_blank" rel="noopener">AJAX </a>call. In this post, we will discuss the solutions for this error in detail and we will also discuss Cross Origin Requests. Here I am going to use <a href="http://sibeeshpassion.com/category/visual-studio/" target="_blank" rel="noopener">Visual Studio</a> 2015, Web API 2. I hope you will like this.</p>
<h2><strong>Background</strong></h2>
<p>I hosted my <a href="http://sibeeshpassion.com/category/web-api" target="_blank" rel="noopener">Web API</a> in a server, and what that API does is, it will just return the data in <a href="http://sibeeshpassion.com/tag/JSON/" target="_blank" rel="noopener">JSON </a>format. But when I try to consume this Web API via an Ajax call, I was getting the error &#8220;No &#8216;Access-Control-Allow-Origin&#8217; header is present on the requested resource&#8221;. I solved the same issues in different ways. Here I am going to share those.</p>
<h2><strong>Using the code</strong></h2>
<p>I assume that you have created a Web API and hosted it in your server. If you are new to Web API, you can always get some information from here <a href="http://sibeeshpassion.com/category/web-api" target="_blank" rel="noopener">Articles Related To Web API </a>.</p>
<p>We all will have some situations where we need to fetch some data from another domain or another site, right? If it is from the same site, you won&#8217;t be facing any issues at all. Like you are calling an Ajax call from the page www.sibeeshpassion.com/Receiver.html to www.sibeeshpassion.com/Sender.html to get the data, here the origin is same. and therefore you will get the data. What happens is when the sender and receiver are not in the same origin. Like you need to get the data from www.Microsoft.com by an Ajax call in www.sibeeshpassion.com/Receiver.html. The browser will not allow you to get the sensitive data from other domain, for the security purpose your browser will return you &#8220;No &#8216;Access-Control-Allow-Origin'&#8221;. To overcome this, we have something called Cross-Origin Resource Sharing (CORS). Basically, the process of allowing other sites to call your Web API is called CORS. According to <a href="https://www.w3.org/TR/cors/" target="_blank" rel="noopener">W3 Org</a> CORS is a standard which tells the server to allow the calls from other origins given. It is much secured than using JSONP(Previously we had been using JSON for getting the data from other domains.).</p>
<h3><strong>Fix To No Access-Control-Allow-Origin header is present</strong></h3>
<p>We can fix this issue in two ways,</p>
<ul>
<li>By using Microsoft.AspNet.WebApi.Cors</li>
<li>By adding header information in Web.config</li>
</ul>
<p>We will explain both now.</p>
<h3><strong>By using Microsoft.AspNet.WebApi.Cors</strong></h3>
<p>To work with this fix, you must include the package By using <em>Microsoft.AspNet.WebApi.Cors</em> from Manage Nuget window.</p>
<p><div id="attachment_11346" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/CORS_In_Manage_NuGet_Package.png"><img decoding="async" aria-describedby="caption-attachment-11346" class="size-large wp-image-11346" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/CORS_In_Manage_NuGet_Package-1024x342.png" alt="CORS_In_Manage_NuGet_Package" width="634" height="212" srcset="/wp-content/uploads/2016/03/CORS_In_Manage_NuGet_Package-1024x342.png 1024w, /wp-content/uploads/2016/03/CORS_In_Manage_NuGet_Package-300x100.png 300w, /wp-content/uploads/2016/03/CORS_In_Manage_NuGet_Package-768x257.png 768w, /wp-content/uploads/2016/03/CORS_In_Manage_NuGet_Package-400x134.png 400w, /wp-content/uploads/2016/03/CORS_In_Manage_NuGet_Package-1795x600.png 1795w, /wp-content/uploads/2016/03/CORS_In_Manage_NuGet_Package.png 1861w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-11346" class="wp-caption-text">CORS_In_Manage_NuGet_Package</p></div></p>
<p>Now got to App_Start folder from your solution. Then click on the file <em>WebApiConfig.cs</em>, this is the file where we set the configuration for our Web API.</p>
<p><div id="attachment_11347" style="width: 308px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/Web_API_Config_Class_File.png"><img decoding="async" aria-describedby="caption-attachment-11347" class="size-full wp-image-11347" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/Web_API_Config_Class_File.png" alt="Web_API_Config_Class_File" width="298" height="221" /></a><p id="caption-attachment-11347" class="wp-caption-text">Web_API_Config_Class_File</p></div></p>
<p>Then you can add the preceding codes in the static function <em>Register</em>.</p>
<p>[csharp]<br />
var cors = new EnableCorsAttribute(&#8220;*&#8221;, &#8220;*&#8221;, &#8220;*&#8221;);<br />
config.EnableCors(cors);<br />
[/csharp]</p>
<p>IF you do this, the CORS will be applied globally for all the Web API controller you have. This is the easiest way of doing it. Now if you want to see the metadata of <em>EnableCorsAttribute</em>, you can see find it below.</p>
<p>[csharp]<br />
// Summary:<br />
// Initializes a new instance of the System.Web.Http.Cors.EnableCorsAttribute class.<br />
//<br />
// Parameters:<br />
// origins:<br />
// Comma-separated list of origins that are allowed to access the resource. Use<br />
// &#8220;*&#8221; to allow all.<br />
//<br />
// headers:<br />
// Comma-separated list of headers that are supported by the resource. Use &#8220;*&#8221; to<br />
// allow all. Use null or empty string to allow none.<br />
//<br />
// methods:<br />
// Comma-separated list of methods that are supported by the resource. Use &#8220;*&#8221; to<br />
// allow all. Use null or empty string to allow none.<br />
public EnableCorsAttribute(string origins, string headers, string methods);<br />
[/csharp]</p>
<p>As it is mentioned, it accepts the parameters origins, headers, methods. Here we pass * to all the three parameters to make everything to be allowable.</p>
<p>You can also try the same as below in the Register function. Here we are going to apply CORS for particular controller, which means it will be applied for all the actions in the controller. Before that make sure you have added the preceding code in your WebApiConfig.cs file</p>
<p>[csharp]<br />
config.EnableCors();<br />
[/csharp]</p>
<p>And in the API controller you need to set the origins,headers,methods as preceding.</p>
<p>[csharp]<br />
using System;<br />
using System.Collections.Generic;<br />
using System.IO;<br />
using System.Linq;<br />
using System.Net;<br />
using System.Net.Http;<br />
using System.Web.Http;<br />
using Newtonsoft.Json;<br />
using Newtonsoft.Json.Converters;<br />
using System.Configuration;<br />
using System.Data;<br />
using System.Data.SqlClient;<br />
using System.Runtime.Serialization;<br />
using System.Text;<br />
using System.Web;<br />
using System.Web.Http.Cors;</p>
<p>namespace APIServiceApplication.Controllers<br />
{</p>
<p>[EnableCors(origins: &#8220;*&#8221;, headers: &#8220;*&#8221;, methods: &#8220;*&#8221;)]<br />
public class DefaultController : ApiController<br />
{<br />
}<br />
}</p>
<p>[/csharp]</p>
<p>Make sure that you have added namespace <em>using System.Web.Http.Cors;</em> to use CORS. You can always disable CORS in an action by using <em>[DisableCors]</em>.</p>
<p>[csharp]<br />
namespace APIServiceApplication.Controllers<br />
{</p>
<p>[EnableCors(origins: &#8220;*&#8221;, headers: &#8220;*&#8221;, methods: &#8220;*&#8221;)]<br />
public class DefaultController : ApiController<br />
{<br />
[DisableCors]<br />
public string XMLData(string id)<br />
{<br />
return &#8220;Your requested product&#8221; + id;<br />
}<br />
}<br />
}<br />
[/csharp]</p>
<p>Here we have disabled CORS for the action <em>XMLData</em>. And again if you need to apply CORS only in a single action, you can do that as follows.</p>
<p>[csharp]<br />
namespace APIServiceApplication.Controllers<br />
{<br />
public class DefaultController : ApiController<br />
{<br />
[EnableCors(origins: &#8220;*&#8221;, headers: &#8220;*&#8221;, methods: &#8220;*&#8221;)]<br />
public string XMLData(string id)<br />
{<br />
return &#8220;Your requested product&#8221; + id;<br />
}<br />
}<br />
}<br />
[/csharp]</p>
<p>I hope you are aware of how to enable CORS now.</p>
<h3><strong>By adding header informations in Web.config</strong></h3>
<p>Another fix we can do is that add some tags in our Web.config file.</p>
<p>[html]<br />
&lt;system.webServer&gt;<br />
&lt;httpProtocol&gt;<br />
&lt;customHeaders&gt;<br />
&lt;add name=&#8221;Access-Control-Allow-Origin&#8221; value=&#8221;*&#8221; /&gt;<br />
&lt;add name=&#8221;Access-Control-Allow-Headers&#8221; value=&#8221;Content-Type&#8221; /&gt;<br />
&lt;add name=&#8221;Access-Control-Allow-Methods&#8221; value=&#8221;GET,POST,PUT,DELETE,OPTIONS&#8221; /&gt;<br />
&lt;add name=&#8221;Access-Control-Allow-Credentials&#8221; value=&#8221;true&#8221; /&gt;<br />
&lt;/customHeaders&gt;<br />
&lt;/httpProtocol&gt;<br />
&lt;/system.webServer&gt;<br />
[/html]</p>
<p>As you can see we have added keys with value for the listed items.</p>
<ul>
<li>Access-Control-Allow-Origin (For Origin)</li>
<li>Access-Control-Allow-Headers (For Headers)</li>
<li>Access-Control-Allow-Methods (For Methods)</li>
</ul>
<p>Now if you go to your server and check, you can see that all the things are configured perfectly. I have configured my API in my server IIS, so I am going to see my Response Header settings in IIS.</p>
<p>Go to the command window and type &#8220;inetmgr&#8221; and click OK, your IIS wilbe openeded shortly, now find your Web API which you have already configured under Default Web Site. Before doing this, please make sure that you have configured IIS in your windows. If you don&#8217;t know how to configure, I strongly recommend you to read <a href="http://sibeeshpassion.com/configure-iis-in-windows/" target="_blank" rel="noopener">Configure IIS in Windows </a>.</p>
<p><div id="attachment_11348" style="width: 248px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/Configured_Web_API_in_IIS.png"><img decoding="async" aria-describedby="caption-attachment-11348" class="size-full wp-image-11348" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/Configured_Web_API_in_IIS.png" alt="Configured_Web_API_in_IIS" width="238" height="92" /></a><p id="caption-attachment-11348" class="wp-caption-text">Configured_Web_API_in_IIS</p></div></p>
<p>Go to Features View and double click on HTTP Response Headers under IIS category.</p>
<p><div id="attachment_11349" style="width: 660px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/HTTP_Response_Headers_In_IIS-e1457687018859.png"><img decoding="async" aria-describedby="caption-attachment-11349" class="size-full wp-image-11349" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/HTTP_Response_Headers_In_IIS-e1457687018859.png" alt="HTTP_Response_Headers_In_IIS" width="650" height="455" srcset="/wp-content/uploads/2016/03/HTTP_Response_Headers_In_IIS-e1457687018859.png 650w, /wp-content/uploads/2016/03/HTTP_Response_Headers_In_IIS-e1457687018859-300x210.png 300w, /wp-content/uploads/2016/03/HTTP_Response_Headers_In_IIS-e1457687018859-400x280.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><p id="caption-attachment-11349" class="wp-caption-text">HTTP_Response_Headers_In_IIS</p></div></p>
<p>You can see all the settings has been configured there.</p>
<p><div id="attachment_11350" style="width: 660px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/03/HTTP_Response_Headers_Available-e1457687318857.png"><img decoding="async" aria-describedby="caption-attachment-11350" class="size-full wp-image-11350" src="http://sibeeshpassion.com/wp-content/uploads/2016/03/HTTP_Response_Headers_Available-e1457687318857.png" alt="HTTP_Response_Headers_Available" width="650" height="456" srcset="/wp-content/uploads/2016/03/HTTP_Response_Headers_Available-e1457687318857.png 650w, /wp-content/uploads/2016/03/HTTP_Response_Headers_Available-e1457687318857-300x210.png 300w, /wp-content/uploads/2016/03/HTTP_Response_Headers_Available-e1457687318857-400x281.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><p id="caption-attachment-11350" class="wp-caption-text">HTTP_Response_Headers_Available</p></div></p>
<h3>CORS in Asp.Net Core application</h3>
<p>Though the mechanism is the same, the way you do things in Asp.Net core application. To set the CORS in asp.net application, you should add the preceding code in your ConfigureServices method in Startup.cs file before the <em><span class="n">services</span><span class="p">.</span><span class="nf">AddMvc</span><span class="p">(); </span></em><span class="p">call</span>.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="csharp">services.AddCors(cors =&gt; cors.AddPolicy("CorsPolicy", builder =&gt; {
 builder.AllowAnyHeader()
  .AllowAnyMethod()
  .AllowAnyOrigin();
}));</pre>
<p>You should also use this policy you have created in the Configure method in Startup.cs before the <em><span class="n">app</span><span class="p">.</span><span class="nf">UseMvc</span><span class="p">(); </span></em><span class="p">call.</span></p>
<pre class="EnlighterJSRAW" data-enlighter-language="csharp">app.UseCors("CorsPolicy");</pre>
<p>That&#8217;s all, now if you run your application, you will be able to fetch the data from your Web API.</p>
<h2><strong>Conclusion</strong></h2>
<p>Did I miss anything that you may think which is needed? Have you ever faced this issue? Did you try Web API yet? I hope you liked this article. Please share me your valuable suggestions and feedback.</p>
<h2><strong>Your turn. What do you think?</strong></h2>
<p>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 am able to.</p>
<p>Kindest Regards<br />
Sibeesh Venu</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.sibeeshpassion.com/fix-to-no-access-control-allow-origin-header-is-present-or-working-with-cross-origin-request-in-asp-net-web-api/feed/</wfw:commentRss>
			<slash:comments>11</slash:comments>
		
		
			</item>
		<item>
		<title>Custom Deferred Grid Using MVC Web API And Angular JS</title>
		<link>https://www.sibeeshpassion.com/custom-deferred-grid-using-mvc-web-api-and-angular-js/</link>
					<comments>https://www.sibeeshpassion.com/custom-deferred-grid-using-mvc-web-api-and-angular-js/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Mon, 29 Feb 2016 00:00:41 +0000</pubDate>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Angular]]></category>
		<category><![CDATA[Web API]]></category>
		<category><![CDATA[Angular JS]]></category>
		<category><![CDATA[Deffered Grid]]></category>
		<category><![CDATA[Grid]]></category>
		<category><![CDATA[Load data while scrolling in Angular JS]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[SqlDataAdapter And Web API]]></category>
		<category><![CDATA[virtualRepeat]]></category>
		<category><![CDATA[Web API With Stored Procedure]]></category>
		<category><![CDATA[Web API Without Entity Data Model]]></category>
		<category><![CDATA[Web API Without Entity Framework]]></category>
		<guid isPermaLink="false">http://sibeecst_passion.com/?p=11296</guid>

					<description><![CDATA[[toc] Introduction In this article we are going to see how to create a custom deferred grid in MVC using Web API and Angular JS. We will be creating a custom UI for the grid and using web API and angular JS $http services we will fetch the data from the database. Normally we uses ADO.Net Entity data model as the model class when we work with a Web API right? Instead of using an Entity data model, here we are going to use our normal SqlDataAdapter and SqlConnection and stored procedure to get the data from our database. We [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>[toc]</p>
<h2>Introduction</h2>
<p>In this article we are going to see how to create a custom deferred grid in <a href="http://sibeeshpassion.com/category/mvc/" target="_blank" rel="noopener">MVC </a>using <a href="http://sibeeshpassion.com/category/web-api" target="_blank" rel="noopener">Web API</a> and <a href="http://sibeeshpassion.com/category/angularjs" target="_blank" rel="noopener">Angular JS</a>. We will be creating a custom UI for the grid and using web API and angular JS $http services we will fetch the data from the database. Normally we uses ADO.Net Entity data model as the model class when we work with a Web API right? Instead of using an Entity data model, here we are going to use our normal SqlDataAdapter and SqlConnection and stored procedure to get the data from our database. We uses Virtual Repeat in Angular JS for loading the data in UI, so that the data will be loaded when ever there is a user action that is scrolling (Virtual Scrolling). So that in the view port we will load only few items first. Now shall we go and see this in detail? I hope you will like this.</p>
<h2><strong>Download the source code</strong></h2>
<p>You can always download the source code here:</p>
<ul>
<li><a href="https://code.msdn.microsoft.com/Custom-Deferred-Grid-Using-de1d1c6e" target="_blank" rel="noopener">Custom Deferred Grid Using MVC Web API And Angular JS</a></li>
<li><a href="http://sibeeshpassion.com/Download/jQuery_Datatable_With_Server_Side_Data_Script.zip" target="_blank" rel="noopener">Trials Database SQL Script</a></li>
</ul>
<h2><strong>Background</strong></h2>
<p>We have so many plugins available to show the data in a grid format. Isn&#8217;t it? if you want to know a few of them, you can find it <a href="http://sibeeshpassion.com/tag/grid/" target="_blank" rel="noopener">here</a>. Now, what if you need to show the data in a grid format without using any additional plugins? What if you need to load the data to that grid dynamically that is whenever the user scrolls the grid? If you could not find the answer to these questions, here in this post I am going to share an option. I hope you will enjoy reading.</p>
<h2><strong>Create an MVC application</strong></h2>
<p>Click File-&gt; New-&gt; Project then select MVC application. Before going to start the coding part, make sure that Angular JS is installed. You can all the items mentioned above from NuGet. Right click on your project name and select Manage NuGet packages.</p>
<p><div id="attachment_11297" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/02/Angular-JS-NuGet-Package-Visual-Studio.png"><img decoding="async" aria-describedby="caption-attachment-11297" class="size-large wp-image-11297" src="http://sibeeshpassion.com/wp-content/uploads/2016/02/Angular-JS-NuGet-Package-Visual-Studio-1024x502.png" alt="Angular JS NuGet Package Visual Studio" width="634" height="311" srcset="/wp-content/uploads/2016/02/Angular-JS-NuGet-Package-Visual-Studio-1024x502.png 1024w, /wp-content/uploads/2016/02/Angular-JS-NuGet-Package-Visual-Studio-300x147.png 300w, /wp-content/uploads/2016/02/Angular-JS-NuGet-Package-Visual-Studio-768x376.png 768w, /wp-content/uploads/2016/02/Angular-JS-NuGet-Package-Visual-Studio-400x196.png 400w, /wp-content/uploads/2016/02/Angular-JS-NuGet-Package-Visual-Studio-1224x600.png 1224w, /wp-content/uploads/2016/02/Angular-JS-NuGet-Package-Visual-Studio.png 1461w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-11297" class="wp-caption-text">Angular JS NuGet Package Visual Studio</p></div></p>
<p>Once you have installed, please make sure that all the items are loaded in your scripts folder.</p>
<h2><strong>Using the code</strong></h2>
<p>I hope everything is set now, then it is time to start our coding. First we will create a controller action and a view. Below is the code snippet of our controller.</p>
<p>[csharp]<br />
using System;<br />
using System.Collections.Generic;<br />
using System.Linq;<br />
using System.Web;<br />
using System.Web.Mvc;<br />
namespace Custom_Deffered_Grid_Using_MVC_Web_API_And_Angular_JS.Controllers<br />
{<br />
public class DefaultController : Controller<br />
{<br />
// GET: Default<br />
public ActionResult Index()<br />
{<br />
return View();<br />
}<br />
}<br />
}<br />
[/csharp]</p>
<p>Here <em>Default/em&gt; is my controller name. Now create a view for this action, and load the needed references.</em></p>
<p>[html]</p>
<p>@{<br />
ViewBag.Title = &#8220;Index&#8221;;<br />
}</p>
<p>&lt;h2&gt;Index&lt;/h2&gt;<br />
&lt;link href=&#8221;~/Content/angular-material.css&#8221; rel=&#8221;stylesheet&#8221; /&gt;<br />
&lt;script src=&#8221;~/scripts/angular.min.js&#8221;&gt;&lt;/script&gt;<br />
&lt;script src=&#8221;~/scripts/angular-route.min.js&#8221;&gt;&lt;/script&gt;<br />
&lt;script src=&#8221;~/scripts/angular-aria.min.js&#8221;&gt;&lt;/script&gt;<br />
&lt;script src=&#8221;~/scripts/angular-animate.min.js&#8221;&gt;&lt;/script&gt;<br />
&lt;script src=&#8221;~/scripts/angular-messages.min.js&#8221;&gt;&lt;/script&gt;<br />
&lt;script src=&#8221;~/scripts/angular-material.js&#8221;&gt;&lt;/script&gt;<br />
&lt;script src=&#8221;~/scripts/svg-assets-cache.js&#8221;&gt;&lt;/script&gt;<br />
&lt;script src=&#8221;~/scripts/Default/Default.js&#8221;&gt;&lt;/script&gt;<br />
[/html]</p>
<p>You can get this files from the source code attached with this article. And the file <em>Default.js</em> is the additional file where we are requested to do our additional scripts. So far the basic implementation of our view is done. Now we will create a Web API and additional model class to fetch the data from the database. Are you ready?</p>
<p>Below is my Web API controller.</p>
<p>[csharp]<br />
using System;<br />
using System.Collections.Generic;<br />
using System.Linq;<br />
using System.Net;<br />
using System.Net.Http;<br />
using System.Web.Http;<br />
using Custom_Deffered_Grid_Using_MVC_Web_API_And_Angular_JS.Models;<br />
namespace Custom_Deffered_Grid_Using_MVC_Web_API_And_Angular_JS.Controllers<br />
{<br />
public class DataAPIController : ApiController<br />
{<br />
DataModel dm = new DataModel();<br />
public string getData(int id)<br />
{<br />
var d = dm.fetchData(id);<br />
return d;<br />
}<br />
}</p>
<p>}<br />
[/csharp]</p>
<p>Have you noticed that I have included <em>using Custom_Deffered_Grid_Using_MVC_Web_API_And_Angular_JS.Models;</em> in the section? This is to ensure that we can use the model classes whatever we have creates so far. In this case <em>DataModel </em>is our model class and we are creating an instance for the same.</p>
<p>[csharp]<br />
DataModel dm = new DataModel();<br />
[/csharp]</p>
<p>The controller action <em>getData</em> accepting the parameter id right? This is actually the page offset value which we are passing from the client side. Now we will create our model class, you can find the code snippets below for that.</p>
<p>[csharp]<br />
using System;<br />
using System.Collections.Generic;<br />
using System.Linq;<br />
using System.Web;<br />
using System.Data;<br />
using System.Data.Sql;<br />
using System.Data.SqlClient;<br />
using System.Configuration;<br />
namespace Custom_Deffered_Grid_Using_MVC_Web_API_And_Angular_JS.Models<br />
{<br />
public class DataModel<br />
{<br />
public string fetchData(int pageOffset)<br />
{<br />
string connection = ConfigurationManager.ConnectionStrings[&#8220;TrialsDBEntities&#8221;].ConnectionString;<br />
using (SqlConnection cn = new SqlConnection(connection))<br />
{<br />
SqlCommand cmd = new SqlCommand(&#8220;usp_Get_SalesOrderDetailPage&#8221;, cn);<br />
cmd.Parameters.Add(&#8220;@pageoffset&#8221;, SqlDbType.Int).Value = pageOffset;<br />
cmd.CommandType = CommandType.StoredProcedure;<br />
try<br />
{<br />
DataTable dt = new DataTable();<br />
SqlDataAdapter da = new SqlDataAdapter(cmd);<br />
cn.Open();<br />
da.Fill(dt);<br />
return GetJson(dt);<br />
}<br />
catch (Exception)<br />
{<br />
throw;<br />
}</p>
<p>}<br />
}<br />
}<br />
}<br />
[/csharp]</p>
<p>As I said before, instead of using an entity model we uses our normal sql connections and sql data adapter to load the data. Before going to use this function, please make sure that you have added the below references.</p>
<p>[csharp]<br />
using System.Data;<br />
using System.Data.Sql;<br />
using System.Data.SqlClient;<br />
using System.Configuration;<br />
[/csharp]</p>
<p>Now coming back to the <em>fetchData </em>function , We uses the connection string <em>TrialsDBEntities</em> from the web config file. So it is mandatory that you must have a connection string with that name in your web config file. Once that is done, we calls the stored procedure <em>usp_Get_SalesOrderDetailPage</em> and fill the data using <em>SqlDataAdapter</em>.</p>
<p>Another thing to be notified here is we are passing that <em>DataTable</em> to a function called <em>GetJson</em>. So you must have the definition for that too.</p>
<p>[csharp]<br />
public string GetJson(DataTable dt)<br />
{<br />
try<br />
{<br />
if (dt == null)<br />
{<br />
throw new ArgumentNullException(&#8220;dt&#8221;);<br />
}<br />
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();<br />
List&lt;Dictionary&lt;string, object&gt;&gt; rows =<br />
new List&lt;Dictionary&lt;string, object&gt;&gt;();<br />
Dictionary&lt;string, object&gt; row = null;<br />
foreach (DataRow dr in dt.Rows)<br />
{<br />
row = new Dictionary&lt;string, object&gt;();<br />
foreach (DataColumn col in dt.Columns)<br />
{<br />
row.Add(col.ColumnName.Trim(), dr[col]);<br />
}<br />
rows.Add(row);<br />
}<br />
return serializer.Serialize(rows);<br />
}<br />
catch (Exception)<br />
{<br />
throw;<br />
}<br />
}<br />
[/csharp]</p>
<p>What this function does it, converting the data table to a <a href="http://sibeeshpassion.com/tag/JSON/" target="_blank" rel="noopener">JSON </a>format. So far, the coding related to Web API is done, now it is time to create a database, table, a stored procedure.</p>
<h3><strong>Create a database</strong></h3>
<p>The following query can be used to create a database in your SQL Server.</p>
<p>[sql]<br />
USE [master]<br />
GO</p>
<p>/****** Object: Database [TrialsDB] Script Date: 25-Feb-16 12:34:32 PM ******/<br />
CREATE DATABASE [TrialsDB]<br />
CONTAINMENT = NONE<br />
ON PRIMARY<br />
( NAME = N&#8217;TrialsDB&#8217;, FILENAME = N&#8217;C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\TrialsDB.mdf&#8217; , SIZE = 3072KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )<br />
LOG ON<br />
( NAME = N&#8217;TrialsDB_log&#8217;, FILENAME = N&#8217;C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\TrialsDB_log.ldf&#8217; , SIZE = 1024KB , MAXSIZE = 2048GB , FILEGROWTH = 10%)<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET COMPATIBILITY_LEVEL = 110<br />
GO</p>
<p>IF (1 = FULLTEXTSERVICEPROPERTY(&#8216;IsFullTextInstalled&#8217;))<br />
begin<br />
EXEC [TrialsDB].[dbo].[sp_fulltext_database] @action = &#8216;enable&#8217;<br />
end<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET ANSI_NULL_DEFAULT OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET ANSI_NULLS OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET ANSI_PADDING OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET ANSI_WARNINGS OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET ARITHABORT OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET AUTO_CLOSE OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET AUTO_CREATE_STATISTICS ON<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET AUTO_SHRINK OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET AUTO_UPDATE_STATISTICS ON<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET CURSOR_CLOSE_ON_COMMIT OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET CURSOR_DEFAULT GLOBAL<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET CONCAT_NULL_YIELDS_NULL OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET NUMERIC_ROUNDABORT OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET QUOTED_IDENTIFIER OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET RECURSIVE_TRIGGERS OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET DISABLE_BROKER<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET AUTO_UPDATE_STATISTICS_ASYNC OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET DATE_CORRELATION_OPTIMIZATION OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET TRUSTWORTHY OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET ALLOW_SNAPSHOT_ISOLATION OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET PARAMETERIZATION SIMPLE<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET READ_COMMITTED_SNAPSHOT OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET HONOR_BROKER_PRIORITY OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET RECOVERY FULL<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET MULTI_USER<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET PAGE_VERIFY CHECKSUM<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET DB_CHAINING OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET FILESTREAM( NON_TRANSACTED_ACCESS = OFF )<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET TARGET_RECOVERY_TIME = 0 SECONDS<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET READ_WRITE<br />
GO<br />
[/sql]</p>
<p>Now we will create a table 🙂</p>
<h3><strong>Create table in database</strong></h3>
<p>Below is the query to create table in database.</p>
<p>[sql]<br />
USE [TrialsDB]<br />
GO</p>
<p>/****** Object: Table [dbo].[SalesOrderDetail] Script Date: 25-Feb-16 12:35:45 PM ******/<br />
SET ANSI_NULLS ON<br />
GO</p>
<p>SET QUOTED_IDENTIFIER ON<br />
GO</p>
<p>CREATE TABLE [dbo].[SalesOrderDetail](<br />
[SalesOrderID] [int] NOT NULL,<br />
[SalesOrderDetailID] [int] IDENTITY(1,1) NOT NULL,<br />
[CarrierTrackingNumber] [nvarchar](25) NULL,<br />
[OrderQty] [smallint] NOT NULL,<br />
[ProductID] [int] NOT NULL,<br />
[SpecialOfferID] [int] NOT NULL,<br />
[UnitPrice] [money] NOT NULL,<br />
[UnitPriceDiscount] [money] NOT NULL,<br />
[LineTotal] AS (isnull(([UnitPrice]*((1.0)-[UnitPriceDiscount]))*[OrderQty],(0.0))),<br />
[rowguid] [uniqueidentifier] ROWGUIDCOL NOT NULL,<br />
[ModifiedDate] [datetime] NOT NULL,<br />
CONSTRAINT [PK_SalesOrderDetail_SalesOrderID_SalesOrderDetailID] PRIMARY KEY CLUSTERED<br />
(<br />
[SalesOrderID] ASC,<br />
[SalesOrderDetailID] ASC<br />
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]<br />
) ON [PRIMARY]</p>
<p>GO<br />
[/sql]</p>
<p>Can we insert some data to the table now?</p>
<h3><strong>Insert data to table</strong></h3>
<p>To insert the data, I will attach a database script file along with the download file, you can either run that or insert some data by using the below query. By the way if you would like to know how to generate scripts with data in SQL Server, you can check <a href="http://sibeeshpassion.com/generate-database-scripts-with-data-in-sql-server/" target="_blank" rel="noopener">here</a>.</p>
<p>[sql]<br />
USE [TrialsDB]<br />
GO</p>
<p>INSERT INTO [dbo].[SalesOrderDetail]<br />
([SalesOrderID]<br />
,[CarrierTrackingNumber]<br />
,[OrderQty]<br />
,[ProductID]<br />
,[SpecialOfferID]<br />
,[UnitPrice]<br />
,[UnitPriceDiscount]<br />
,[rowguid]<br />
,[ModifiedDate])<br />
VALUES<br />
(&lt;SalesOrderID, int,&gt;<br />
,&lt;CarrierTrackingNumber, nvarchar(25),&gt;<br />
,&lt;OrderQty, smallint,&gt;<br />
,&lt;ProductID, int,&gt;<br />
,&lt;SpecialOfferID, int,&gt;<br />
,&lt;UnitPrice, money,&gt;<br />
,&lt;UnitPriceDiscount, money,&gt;<br />
,&lt;rowguid, uniqueidentifier,&gt;<br />
,&lt;ModifiedDate, datetime,&gt;)<br />
GO<br />
[/sql]</p>
<p>Along with this, we can create a new stored procedure which will fetch the data. Following is the query to create the stored procedure.</p>
<p>[sql]<br />
USE [TrialsDB]<br />
GO<br />
/****** Object: StoredProcedure [dbo].[usp_Get_SalesOrderDetailPage] Script Date: 25-Feb-16 12:53:07 PM ******/<br />
SET ANSI_NULLS ON<br />
GO<br />
SET QUOTED_IDENTIFIER ON<br />
GO<br />
&#8212; =============================================<br />
&#8212; Author: &lt;Author,Sibeesh Venu&gt;<br />
&#8212; Create date: &lt;Create Date, 18-Feb-2016&gt;<br />
&#8212; Description: &lt;Description,To fetch SalesOrderDetail Page Wise&gt;<br />
&#8212; =============================================<br />
ALTER PROCEDURE [dbo].[usp_Get_SalesOrderDetailPage] @pageOffset int=0 AS BEGIN &#8212; SET NOCOUNT ON added to prevent extra result sets from<br />
&#8212; interfering with SELECT statements.</p>
<p>SET NOCOUNT ON;</p>
<p>WITH CTE_Sales(SlNo, SalesOrderID,SalesOrderDetailID,CarrierTrackingNumber,OrderQty,ProductID,UnitPrice,ModifiedDate) AS<br />
( SELECT ROW_NUMBER() over (<br />
ORDER BY ModifiedDate DESC) AS SlNo,<br />
SalesOrderID,<br />
SalesOrderDetailID,<br />
CarrierTrackingNumber,<br />
OrderQty,<br />
ProductID,<br />
UnitPrice,<br />
ModifiedDate<br />
FROM dbo.SalesOrderDetail)<br />
SELECT *<br />
FROM CTE_Sales<br />
WHERE SlNo&gt;=@pageOffset<br />
AND SlNo&lt;@pageOffset+10 END</p>
<p>&#8211;[usp_Get_SalesOrderDetailPage] 4<br />
[/sql]</p>
<p>Here we are using Common Table Expressions in SQL Server. If you are new to CTE, you can always see here <a href="http://sibeeshpassion.com/stored-procedure-with-common-table-expression-or-cte/" target="_blank" rel="noopener">Common Table Expression Example</a> for some more informations regarding that. It seems the database is ready with the data now. Then we can go back to our view. We will change our view as follows with the custom styles.</p>
<p>[html]</p>
<p>@{<br />
ViewBag.Title = &#8220;Index&#8221;;<br />
}</p>
<p>&lt;h2&gt;Index&lt;/h2&gt;<br />
&lt;link href=&#8221;~/Content/angular-material.css&#8221; rel=&#8221;stylesheet&#8221; /&gt;<br />
&lt;style&gt;<br />
.virtualRepeatdemoDeferredLoading #vertical-container {<br />
padding: 10px;<br />
border: 1px solid #ccc;<br />
border-radius: 5px;<br />
box-shadow: 1px 10px 10px 1px #ccc;<br />
background-color: #fff;<br />
width: 40%;<br />
height: 390px;<br />
margin: 20px;<br />
}</p>
<p>.virtualRepeatdemoDeferredLoading .repeated-item {<br />
border-bottom: 1px solid #ddd;<br />
box-sizing: border-box;<br />
height: 40px;<br />
padding: 10px;<br />
border: 1px solid #ccc;<br />
border-radius: 5px;<br />
box-shadow: 1px 10px 10px 1px #ccc;<br />
background-color: #fff;<br />
width: 90%;<br />
height: 120px;<br />
margin: 20px;<br />
color: #aaa;<br />
font-size: 12px;<br />
line-height: 20px;<br />
}</p>
<p>.virtualRepeatdemoDeferredLoading md-content {<br />
margin: 16px;<br />
}</p>
<p>.virtualRepeatdemoDeferredLoading md-virtual-repeat-container {<br />
border: solid 1px grey;<br />
}</p>
<p>.virtualRepeatdemoDeferredLoading .md-virtual-repeat-container .md-virtual-repeat-offsetter div {<br />
padding-left: 16px;<br />
}</p>
<p>#introduction {<br />
border-bottom: 1px solid #ddd;<br />
box-sizing: border-box;<br />
height: 40px;<br />
padding: 10px;<br />
border: 1px solid #ccc;<br />
border-radius: 5px;<br />
box-shadow: 1px 10px 10px 1px #ccc;<br />
background-color: #fff;<br />
width: 98%;<br />
height: 70px;<br />
color: #aaa;<br />
font-size: 12px;<br />
line-height: 25px;<br />
}<br />
&lt;/style&gt;<br />
&lt;div ng-controller=&#8221;AppCtrl as ctrl&#8221; ng-cloak=&#8221;&#8221; class=&#8221;virtualRepeatdemoDeferredLoading&#8221; ng-app=&#8221;MyApp&#8221;&gt;<br />
&lt;md-content layout=&#8221;column&#8221;&gt;<br />
&lt;div id=&#8221;introduction&#8221;&gt;<br />
&lt;p&gt;<br />
Please scroll the Grid to load the data from database. This is a simple demo of deffered or virtual data loading in Angular JS.<br />
We created this application MVC with Web API to fetch the data. I hope you enjoyed the demo. Please visit again 🙂<br />
&lt;/p&gt;<br />
&lt;/div&gt;<br />
&lt;md-virtual-repeat-container id=&#8221;vertical-container&#8221;&gt;<br />
&lt;div md-virtual-repeat=&#8221;item in ctrl.dynamicItems&#8221; md-on-demand=&#8221;&#8221; class=&#8221;repeated-item&#8221; flex=&#8221;&#8221;&gt;<br />
&lt;div&gt; &lt;b&gt;SlNo:&lt;/b&gt; {{item.SlNo}}, &lt;b&gt;SalesOrderID:&lt;/b&gt; {{item.SalesOrderID}}&lt;/div&gt;<br />
&lt;div&gt; &lt;b&gt;SalesOrderDetailID:&lt;/b&gt; {{item.SalesOrderDetailID}}, &lt;b&gt;CarrierTrackingNumber:&lt;/b&gt; {{item.CarrierTrackingNumber}}&lt;/div&gt;<br />
&lt;div&gt; &lt;b&gt;OrderQty:&lt;/b&gt; {{item.OrderQty}}, &lt;b&gt;ProductID:&lt;/b&gt; {{item.ProductID}}&lt;/div&gt;<br />
&lt;div&gt; &lt;b&gt;UnitPrice:&lt;/b&gt; {{item.UnitPrice}}&lt;/div&gt;<br />
&lt;/div&gt;<br />
&lt;/md-virtual-repeat-container&gt;</p>
<p>&lt;/md-content&gt;</p>
<p>&lt;/div&gt;<br />
&lt;script src=&#8221;~/scripts/angular.min.js&#8221;&gt;&lt;/script&gt;<br />
&lt;script src=&#8221;~/scripts/angular-route.min.js&#8221;&gt;&lt;/script&gt;<br />
&lt;script src=&#8221;~/scripts/angular-aria.min.js&#8221;&gt;&lt;/script&gt;<br />
&lt;script src=&#8221;~/scripts/angular-animate.min.js&#8221;&gt;&lt;/script&gt;<br />
&lt;script src=&#8221;~/scripts/angular-messages.min.js&#8221;&gt;&lt;/script&gt;<br />
&lt;script src=&#8221;~/scripts/angular-material.js&#8221;&gt;&lt;/script&gt;<br />
&lt;script src=&#8221;~/scripts/svg-assets-cache.js&#8221;&gt;&lt;/script&gt;<br />
&lt;script src=&#8221;~/scripts/Default/Default.js&#8221;&gt;&lt;/script&gt;<br />
[/html]</p>
<p>As you can see form the above code, our Angular JS controller is <em>ng-controller=&#8221;AppCtrl as ctrl&#8221;</em> and the Angular JS app is <em>ng-app=&#8221;MyApp&#8221;</em>. We uses <em>md-virtual-repeat</em> as a repeater control, so that it can be used to loop through the object <em>item in ctrl.dynamicItems</em>. Now it is time to create our Angular JS scripts. Shall we?</p>
<p>We can create our Angular App and Controller as follows.</p>
<p>[js]<br />
(function () {<br />
&#8216;use strict&#8217;;<br />
angular<br />
.module(&#8216;MyApp&#8217;, [&#8216;ngMaterial&#8217;, &#8216;ngMessages&#8217;, &#8216;material.svgAssetsCache&#8217;])<br />
.controller(&#8216;AppCtrl&#8217;, function ($http, $timeout) {<br />
});<br />
})();<br />
[/js]</p>
<p>Now in the controller we will add a function with some predefined items as follows.</p>
<p>[js]<br />
var DynamicItems = function () {<br />
this.loadedPages = {};<br />
this.numItems = 0;<br />
this.PAGE_SIZE = 10;<br />
this.fetchNumItems_();<br />
};<br />
[/js]</p>
<p>Here <em>loadedPages</em> is the data collection which is keyed by the page number (Our parameter id in the controller). And <em>numItems</em> is the total number of items. <em>PAGE_SIZE</em> is the number of items to be fetched from each requests.</p>
<p>Now we will create a function to calculate the length of the records.</p>
<p>[js]<br />
DynamicItems.prototype.getLength = function () {<br />
return this.numItems;<br />
};<br />
[/js]</p>
<p>This <em>numItems</em> can be set in the below function.</p>
<p>[js]<br />
DynamicItems.prototype.fetchNumItems_ = function () {<br />
$timeout(angular.noop, 300).then(angular.bind(this, function () {<br />
this.numItems = 1000;<br />
}));<br />
};<br />
[/js]</p>
<p>Here we are setting the <em>numItems </em> as 1000 for demo purposes, you can always get the count from database and assign it here with a $http request as we load the data from database here, you are yet to see that, no worries.</p>
<p>Below is the function to get the item by index.</p>
<p>[js]<br />
DynamicItems.prototype.getItemAtIndex = function (index) {<br />
var pageNumber = Math.floor(index / this.PAGE_SIZE);<br />
var page = this.loadedPages[pageNumber];</p>
<p>if (page) {<br />
return page[index % this.PAGE_SIZE];<br />
} else if (page !== null) {<br />
this.fetchPage_(pageNumber);<br />
}<br />
};<br />
[/js]</p>
<p>Here is the main part that to load the data from database using a $http service in Angular JS.</p>
<p>[js]<br />
DynamicItems.prototype.fetchPage_ = function (pageNumber) {<br />
this.loadedPages[pageNumber] = null;<br />
$timeout(angular.noop, 300).then(angular.bind(this, function () {<br />
var thisObj = this;<br />
this.loadedPages[pageNumber] = [];<br />
var pageOffset = pageNumber * this.PAGE_SIZE;<br />
var myData;<br />
var url = &#8221;;<br />
url = &#8216;api/DataAPI/&#8217; + pageOffset;<br />
$http({<br />
method: &#8216;GET&#8217;,<br />
url: url,<br />
}).then(function successCallback(response) {<br />
// this callback will be called asynchronously<br />
// when the response is available<br />
myData = JSON.parse(response.data);<br />
pushLoadPages(thisObj, myData)<br />
}, function errorCallback(response) {<br />
console.log(&#8216;Oops! Something went wrong while fetching the data. Status Code: &#8216; + response.status + &#8216; Status statusText: &#8216; + response.statusText);<br />
// called asynchronously if an error occurs<br />
// or server returns response with an error status.<br />
});<br />
}));<br />
};<br />
[/js]</p>
<p>As you can see calls our Web API ( <em>url = &#8216;api/DataAPI/&#8217; + pageOffset;</em>) from $http service, the callback function <em>successCallback</em> will get the data from database as a response. Once we get the response, we will pass the data to a function <em>pushLoadPages</em> to push the data items to the <em>loadedPages</em>. Cool right? Below is the code snippets for that function.</p>
<p>[js]<br />
function pushLoadPages(thisObj, servData) {<br />
if (servData != undefined) {<br />
for (var i = 0; i &lt; servData.length; i++) {<br />
thisObj.loadedPages[pageNumber].push(servData[i]);<br />
}<br />
}<br />
}<br />
[/js]</p>
<p>Here is the complete code for our Angular JS.</p>
<h3><strong>Angular JS Complete Code </strong></h3>
<p>[js]<br />
(function () {<br />
&#8216;use strict&#8217;;<br />
angular<br />
.module(&#8216;MyApp&#8217;, [&#8216;ngMaterial&#8217;, &#8216;ngMessages&#8217;, &#8216;material.svgAssetsCache&#8217;])<br />
.controller(&#8216;AppCtrl&#8217;, function ($http, $timeout) {<br />
var DynamicItems = function () {<br />
this.loadedPages = {};<br />
this.numItems = 0;<br />
this.PAGE_SIZE = 10;<br />
this.fetchNumItems_();<br />
};<br />
DynamicItems.prototype.getItemAtIndex = function (index) {<br />
var pageNumber = Math.floor(index / this.PAGE_SIZE);<br />
var page = this.loadedPages[pageNumber];</p>
<p>if (page) {<br />
return page[index % this.PAGE_SIZE];<br />
} else if (page !== null) {<br />
this.fetchPage_(pageNumber);<br />
}<br />
};<br />
DynamicItems.prototype.getLength = function () {<br />
return this.numItems;<br />
};<br />
DynamicItems.prototype.fetchPage_ = function (pageNumber) {<br />
this.loadedPages[pageNumber] = null;<br />
$timeout(angular.noop, 300).then(angular.bind(this, function () {<br />
var thisObj = this;<br />
this.loadedPages[pageNumber] = [];<br />
var pageOffset = pageNumber * this.PAGE_SIZE;<br />
var myData;<br />
var url = &#8221;;<br />
url = &#8216;api/DataAPI/&#8217; + pageOffset;<br />
$http({<br />
method: &#8216;GET&#8217;,<br />
url: url,<br />
}).then(function successCallback(response) {<br />
// this callback will be called asynchronously<br />
// when the response is available<br />
myData = JSON.parse(response.data);<br />
pushLoadPages(thisObj, myData)<br />
}, function errorCallback(response) {<br />
console.log(&#8216;Oops! Something went wrong while fetching the data. Status Code: &#8216; + response.status + &#8216; Status statusText: &#8216; + response.statusText);<br />
// called asynchronously if an error occurs<br />
// or server returns response with an error status.<br />
});<br />
function pushLoadPages(thisObj, servData) {<br />
if (servData != undefined) {<br />
for (var i = 0; i &lt; servData.length; i++) {<br />
thisObj.loadedPages[pageNumber].push(servData[i]);<br />
}<br />
}<br />
}<br />
}));<br />
};<br />
DynamicItems.prototype.fetchNumItems_ = function () {<br />
$timeout(angular.noop, 300).then(angular.bind(this, function () {<br />
this.numItems = 1000;<br />
}));<br />
};<br />
this.dynamicItems = new DynamicItems();<br />
});<br />
})();<br />
[/js]</p>
<p>Now it is time to see the output.</p>
<h2><strong>Output</strong></h2>
<p><div id="attachment_11299" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/02/Custom-Deffered-Grid-Using-MVC-Web-API-And-Angular-JS-Output.png"><img decoding="async" aria-describedby="caption-attachment-11299" class="size-large wp-image-11299" src="http://sibeeshpassion.com/wp-content/uploads/2016/02/Custom-Deffered-Grid-Using-MVC-Web-API-And-Angular-JS-Output-1024x577.png" alt="Custom Deffered Grid Using MVC Web API And Angular JS Output" width="634" height="357" srcset="/wp-content/uploads/2016/02/Custom-Deffered-Grid-Using-MVC-Web-API-And-Angular-JS-Output-1024x577.png 1024w, /wp-content/uploads/2016/02/Custom-Deffered-Grid-Using-MVC-Web-API-And-Angular-JS-Output-300x169.png 300w, /wp-content/uploads/2016/02/Custom-Deffered-Grid-Using-MVC-Web-API-And-Angular-JS-Output-768x433.png 768w, /wp-content/uploads/2016/02/Custom-Deffered-Grid-Using-MVC-Web-API-And-Angular-JS-Output-400x226.png 400w, /wp-content/uploads/2016/02/Custom-Deffered-Grid-Using-MVC-Web-API-And-Angular-JS-Output-1064x600.png 1064w, /wp-content/uploads/2016/02/Custom-Deffered-Grid-Using-MVC-Web-API-And-Angular-JS-Output.png 1135w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-11299" class="wp-caption-text">Custom Deferred Grid Using MVC Web API And Angular JS Output</p></div></p>
<p><div id="attachment_11300" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/02/Custom-Deffered-Grid-Using-MVC-Web-API-And-Angular-JS-Deferred-Output.png"><img decoding="async" aria-describedby="caption-attachment-11300" class="size-large wp-image-11300" src="http://sibeeshpassion.com/wp-content/uploads/2016/02/Custom-Deffered-Grid-Using-MVC-Web-API-And-Angular-JS-Deferred-Output-1024x572.png" alt="Custom Deffered Grid Using MVC Web API And Angular JS Deferred Output" width="634" height="354" srcset="/wp-content/uploads/2016/02/Custom-Deffered-Grid-Using-MVC-Web-API-And-Angular-JS-Deferred-Output-1024x572.png 1024w, /wp-content/uploads/2016/02/Custom-Deffered-Grid-Using-MVC-Web-API-And-Angular-JS-Deferred-Output-300x168.png 300w, /wp-content/uploads/2016/02/Custom-Deffered-Grid-Using-MVC-Web-API-And-Angular-JS-Deferred-Output-768x429.png 768w, /wp-content/uploads/2016/02/Custom-Deffered-Grid-Using-MVC-Web-API-And-Angular-JS-Deferred-Output-400x223.png 400w, /wp-content/uploads/2016/02/Custom-Deffered-Grid-Using-MVC-Web-API-And-Angular-JS-Deferred-Output-1074x600.png 1074w, /wp-content/uploads/2016/02/Custom-Deffered-Grid-Using-MVC-Web-API-And-Angular-JS-Deferred-Output.png 1137w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-11300" class="wp-caption-text">Custom Deferred Grid Using MVC Web API And Angular JS Deferred Output</p></div></p>
<p>Have a happy coding.</p>
<h2><strong>Reference</strong></h2>
<ul>
<li><a href="https://material.angularjs.org/latest/" target="_blank" rel="noopener">Angular JS Materials </a></li>
</ul>
<h2><strong>Conclusion</strong></h2>
<p>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.</p>
<h2><strong>Your turn. What do you think?</strong></h2>
<p>A blog isn&#8217;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 Stack Overflow instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I can.</p>
<p>Kindest Regards<br />
Sibeesh Venu</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.sibeeshpassion.com/custom-deferred-grid-using-mvc-web-api-and-angular-js/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>TagIt Control With Data From Database Using Angular JS In MVC Web API</title>
		<link>https://www.sibeeshpassion.com/tagit-control-with-data-from-database-using-angular-js-in-mvc-web-api/</link>
					<comments>https://www.sibeeshpassion.com/tagit-control-with-data-from-database-using-angular-js-in-mvc-web-api/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Thu, 25 Feb 2016 00:00:46 +0000</pubDate>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Angular]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[Web API]]></category>
		<category><![CDATA[Angular JS]]></category>
		<category><![CDATA[JQuery]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[TagIt]]></category>
		<category><![CDATA[TagIt Tags From Database]]></category>
		<guid isPermaLink="false">http://sibeecst_passion.com/?p=11245</guid>

					<description><![CDATA[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 [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>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. </p>
<li><a href="http://sibeeshpassion.com/category/angularjs/" target="_blank" rel="noopener">AngularJS Tips, Tricks, Blogs</a></li>
<li><a href="http://sibeeshpassion.com/category/mvc/" target="_blank" rel="noopener">MVC Tips, Tricks, Blogs</a></li>
<li><a href="http://sibeeshpassion.com/category/web-api/" target="_blank" rel="noopener">Web API Tips, Tricks, Blogs</a></li>
<p>As the article title implies, we are actually going to load the tags from a table called tblTags from <a href="http://sibeeshpassion.com/category/SQL/" target="_blank" rel="noopener">SQL </a>Server database.  So now we will go and create our application. I hope you will like this. </p>
<p><strong>Download the source code</strong></p>
<p>You can always download the source code here: <a href="https://code.msdn.microsoft.com/TagIt-Control-With-Data-aa3371f7" target="_blank" rel="noopener">Load Tags From Database Using Angular JS In MVC Web API</a></p>
<p><strong>Background</strong></p>
<p>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&#8217;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.</p>
<p><strong>Create a MVC application</strong></p>
<p>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. </p>
<li>Angular JS</li>
<li>TagIt Plugin</li>
<li>jQuery</li>
<p>You can all the items mentioned above from NuGet. Right click on your project name and select Manage NuGet packages.</p>
<p><div id="attachment_11235" style="width: 660px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/02/Manage-NuGet-Package-Window-e1455700665396.png"><img decoding="async" aria-describedby="caption-attachment-11235" src="http://sibeeshpassion.com/wp-content/uploads/2016/02/Manage-NuGet-Package-Window-e1455700665396.png" alt="Manage NuGet Package Window" width="650" height="432" class="size-full wp-image-11235" srcset="/wp-content/uploads/2016/02/Manage-NuGet-Package-Window-e1455700665396.png 650w, /wp-content/uploads/2016/02/Manage-NuGet-Package-Window-e1455700665396-300x199.png 300w, /wp-content/uploads/2016/02/Manage-NuGet-Package-Window-e1455700665396-400x266.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><p id="caption-attachment-11235" class="wp-caption-text">Manage NuGet Package Window</p></div></p>
<p>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. </p>
<p><strong>Using the code</strong></p>
<p>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. </p>
<p><em>Include the references in your _Layout.cshtml</em></p>
<p>As we have already installed all the packages we need, now we need to add the references, right?</p>
<p>[html]<br />
@RenderBody()</p>
<p>    @Scripts.Render(&quot;~/bundles/jquery&quot;)<br />
    &lt;script src=&quot;~/Scripts/jquery-2.2.0.js&quot;&gt;&lt;/script&gt;<br />
    &lt;script src=&quot;~/Content/jquery-ui.min.js&quot;&gt;&lt;/script&gt;<br />
    &lt;script src=&quot;~/Scripts/angular.js&quot;&gt;&lt;/script&gt;<br />
    &lt;script src=&quot;~/Scripts/angular-route.js&quot;&gt;&lt;/script&gt;<br />
    &lt;script src=&quot;~/Scripts/tag-it.min.js&quot;&gt;&lt;/script&gt;<br />
    &lt;script src=&quot;~/Scripts/MyScripts/TagScripts.js&quot;&gt;&lt;/script&gt;<br />
    @RenderSection(&quot;scripts&quot;, required: false)<br />
[/html]</p>
<p>Here <em>TagScripts.js</em> is the JavaScript file where we are going to write our own scripts.  </p>
<p><em>Set the changes in View</em></p>
<p>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. </p>
<p>[html]<br />
&lt;div ng-app=&quot;tagApp&quot;&gt;<br />
    &lt;div ng-controller=&quot;tagController&quot;&gt;<br />
        &lt;ul id=&quot;tags&quot;&gt;&lt;/ul&gt;<br />
        &lt;div id=&quot;error&quot;&gt;Nothing found!&lt;/div&gt;<br />
    &lt;/div&gt;<br />
&lt;/div&gt;<br />
[/html]</p>
<p>You can give a style as follows if you want.</p>
<p>[css]<br />
&lt;style&gt;<br />
    #tags {<br />
        width: 25%;<br />
    }</p>
<p>    #error {<br />
        display:none;<br />
        font-weight: bold;<br />
        color: #1c94c4;<br />
        font-family: Trebuchet MS,Tahoma,Verdana,Arial,sans-serif;<br />
        font-size: 1.1em;<br />
    }<br />
&lt;/style&gt;<br />
[/css]</p>
<p>Oops!, I forgot to mention, please do not forget to include the CSS style sheets. </p>
<p>[html]<br />
&lt;link href=&quot;~/Content/jquery-ui.css&quot; rel=&quot;stylesheet&quot; /&gt;<br />
&lt;link href=&quot;~/Content/jquery.tagit.css&quot; rel=&quot;stylesheet&quot; /&gt;<br />
[/html]</p>
<p>Now we can write the scripts in our TagScripts.js file. </p>
<p><em>Create Angular App</em></p>
<p>You can create an Angular module as follows. </p>
<p>[js]<br />
var app;<br />
    //Angular App<br />
    app = angular.module(&#8216;tagApp&#8217;, []);<br />
[/js]</p>
<blockquote><p>Here the module name must be same as we have given in ng-app in our view. </p></blockquote>
<p><em>Create Angular Controller</em></p>
<p>You can create an Angular Controller as follows. </p>
<p>[js]<br />
app.controller(&#8216;tagController&#8217;, function ($scope) {<br />
        $(&quot;#tags&quot;).tagit({<br />
            availableTags: availableTags,<br />
            autocomplete: { delay: 0, minLength: 1 },<br />
            beforeTagAdded: function (event, ui) {<br />
                if ($.inArray(ui.tagLabel, availableTags) &lt; 0) {<br />
                    $(&#8216;#error&#8217;).show();<br />
                    return false;<br />
                } else {<br />
                    $(&#8216;#error&#8217;).hide();<br />
                }<br />
            }<br />
        });<br />
    });<br />
[/js]</p>
<p>As you can see we have called tagit() function to initialize the tagit control. Below are the explanations to the options we have given.</p>
<li>availableTags</li>
<p>availableTags are the source we need to apply to the control so that the given items can be shown on user actions. </p>
<li>autocomplelte</i>
<p>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</p>
<li>beforeTagAdded</li>
<p>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.</p>
<p>[js]<br />
if ($.inArray(ui.tagLabel, availableTags) &lt; 0) {<br />
                    $(&#8216;#error&#8217;).show();<br />
                    return false;<br />
                } else {<br />
                    $(&#8216;#error&#8217;).hide();<br />
                }<br />
[/js]</p>
<p>If user tries to add a new tag, we will show the alert div which we already set in our view.</p>
<p>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.  </p>
<p><div id="attachment_11260" style="width: 562px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/02/Tag_It_Control_Defined_Array.png"><img decoding="async" aria-describedby="caption-attachment-11260" src="http://sibeeshpassion.com/wp-content/uploads/2016/02/Tag_It_Control_Defined_Array.png" alt="Tag_It_Control_Defined_Array" width="552" height="169" class="size-full wp-image-11260" srcset="/wp-content/uploads/2016/02/Tag_It_Control_Defined_Array.png 552w, /wp-content/uploads/2016/02/Tag_It_Control_Defined_Array-300x92.png 300w, /wp-content/uploads/2016/02/Tag_It_Control_Defined_Array-400x122.png 400w" sizes="(max-width: 552px) 100vw, 552px" /></a><p id="caption-attachment-11260" class="wp-caption-text">Tag_It_Control_Defined_Array</p></div></p>
<p><div id="attachment_11261" style="width: 557px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/02/Tag_It_Control_Defined_Array_If_Nothing_Found.png"><img decoding="async" aria-describedby="caption-attachment-11261" src="http://sibeeshpassion.com/wp-content/uploads/2016/02/Tag_It_Control_Defined_Array_If_Nothing_Found.png" alt="Tag_It_Control_Defined_Array_If_Nothing_Found" width="547" height="135" class="size-full wp-image-11261" srcset="/wp-content/uploads/2016/02/Tag_It_Control_Defined_Array_If_Nothing_Found.png 547w, /wp-content/uploads/2016/02/Tag_It_Control_Defined_Array_If_Nothing_Found-300x74.png 300w, /wp-content/uploads/2016/02/Tag_It_Control_Defined_Array_If_Nothing_Found-400x99.png 400w" sizes="(max-width: 547px) 100vw, 547px" /></a><p id="caption-attachment-11261" class="wp-caption-text">Tag_It_Control_Defined_Array_If_Nothing_Found</p></div></p>
<p>It seems everything is fine, thank god we don&#8217;t need any debugging 🙂</p>
<p>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.</p>
<p><div id="attachment_11238" style="width: 614px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/02/Web_API_controller.png"><img decoding="async" aria-describedby="caption-attachment-11238" src="http://sibeeshpassion.com/wp-content/uploads/2016/02/Web_API_controller.png" alt="Web_API_controller" width="604" height="396" class="size-full wp-image-11238" srcset="/wp-content/uploads/2016/02/Web_API_controller.png 604w, /wp-content/uploads/2016/02/Web_API_controller-300x197.png 300w, /wp-content/uploads/2016/02/Web_API_controller-400x262.png 400w" sizes="(max-width: 604px) 100vw, 604px" /></a><p id="caption-attachment-11238" class="wp-caption-text">Web_API_controller</p></div></p>
<p>So our Web API controller is ready, then it is time to go to do some Angular JS scripts, don&#8217;t worry we will come back here. </p>
<p>We need to make changes to our Angular JS controller <em>tagController </em> as follows. </p>
<p>[js]<br />
    //Angular Controller<br />
    app.controller(&#8216;tagController&#8217;, function ($scope, tagService) {<br />
        //Angular service call<br />
        var tgs = tagService.getTags();<br />
        if (tgs != undefined) {<br />
            tgs.then(function (d) {<br />
                availableTags = [];<br />
                for (var i = 0; i &lt; d.data.length; i++) {<br />
                    availableTags.push(d.data[i].tagName);<br />
                }</p>
<p>                $(&quot;#tags&quot;).tagit({<br />
                    availableTags: availableTags,<br />
                    autocomplete: { delay: 0, minLength: 1 },<br />
                    beforeTagAdded: function (event, ui) {<br />
                        if ($.inArray(ui.tagLabel, availableTags) &lt; 0) {<br />
                            $(&#8216;#error&#8217;).show();<br />
                            return false;<br />
                        } else {<br />
                            $(&#8216;#error&#8217;).hide();<br />
                        }<br />
                    }<br />
                });<br />
                console.log(JSON.stringify(availableTags));<br />
            }, function (error) {<br />
                console.log(&#8216;Oops! Something went wrong while fetching the data.&#8217;);<br />
            });<br />
        }<br />
    });<br />
[/js]</p>
<p>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?</p>
<p>[js]<br />
    //Angular Service<br />
    app.service(&#8216;tagService&#8217;, function ($http) {<br />
        //call the web api controller<br />
        this.getTags = function () {<br />
            return $http({<br />
                method: &#8216;get&#8217;,<br />
                url: &#8216;api/tag&#8217;<br />
            });<br />
        }<br />
    });<br />
[/js]</p>
<p>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. </p>
<p>[js]<br />
/* Using jQuery */</p>
<p>$(function () {<br />
    var availableTags = [<br />
      &quot;ActionScript&quot;,<br />
      &quot;AppleScript&quot;,<br />
      &quot;Asp&quot;,<br />
      &quot;BASIC&quot;,<br />
      &quot;C&quot;,<br />
      &quot;C++&quot;,<br />
      &quot;Clojure&quot;,<br />
      &quot;COBOL&quot;,<br />
      &quot;ColdFusion&quot;,<br />
      &quot;Erlang&quot;,<br />
      &quot;Fortran&quot;,<br />
      &quot;Groovy&quot;,<br />
      &quot;Haskell&quot;,<br />
      &quot;Java&quot;,<br />
      &quot;JavaScript&quot;,<br />
      &quot;Lisp&quot;,<br />
      &quot;Perl&quot;,<br />
      &quot;PHP&quot;,<br />
      &quot;Python&quot;,<br />
      &quot;Ruby&quot;,<br />
      &quot;Scala&quot;,<br />
      &quot;Scheme&quot;<br />
    ];<br />
    //Load the available tags from database start<br />
    $.ajax({<br />
        type: &#8216;GET&#8217;,<br />
        dataType: &#8216;json&#8217;,<br />
        contentType: &#8216;application/json;charset=utf-8&#8217;,<br />
        url: &#8216;http://localhost:56076/api/Tag&#8217;,<br />
        success: function (data) {<br />
            try {<br />
                if (data.length &gt; 0) {<br />
                    availableTags = data;<br />
                }<br />
            } catch (e) {<br />
                console.log(&#8216;Error while formatting the data : &#8216; + e.message)<br />
            }<br />
        },<br />
        error: function (xhrequest, error, thrownError) {<br />
            console.log(&#8216;Error while ajax call: &#8216; + error)<br />
        }<br />
    });<br />
    //Load the available tags from database end</p>
<p>    $(&quot;#tags&quot;).tagit({<br />
        availableTags: availableTags,<br />
        autocomplete: { delay: 0, minLength: 1 },<br />
        beforeTagAdded: function (event, ui) {<br />
            if ($.inArray(ui.tagLabel, availableTags) &lt; 0) {<br />
                $(&#8216;#error&#8217;).show();<br />
                return false;<br />
            } else {<br />
                $(&#8216;#error&#8217;).hide();<br />
            }<br />
        }<br />
    });<br />
});<br />
[/js]</p>
<p>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?</p>
<p><strong>Create a database</strong></p>
<p>The following query can be used to create a database in your SQL Server.</p>
<p>[sql]<br />
USE [master]<br />
GO</p>
<p>/****** Object:  Database [TrialsDB]    Script Date: 17-Feb-16 10:21:17 PM ******/<br />
CREATE DATABASE [TrialsDB]<br />
 CONTAINMENT = NONE<br />
 ON  PRIMARY<br />
( NAME = N&#8217;TrialsDB&#8217;, FILENAME = N&#8217;C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\TrialsDB.mdf&#8217; , SIZE = 3072KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )<br />
 LOG ON<br />
( NAME = N&#8217;TrialsDB_log&#8217;, FILENAME = N&#8217;C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\TrialsDB_log.ldf&#8217; , SIZE = 1024KB , MAXSIZE = 2048GB , FILEGROWTH = 10%)<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET COMPATIBILITY_LEVEL = 110<br />
GO</p>
<p>IF (1 = FULLTEXTSERVICEPROPERTY(&#8216;IsFullTextInstalled&#8217;))<br />
begin<br />
EXEC [TrialsDB].[dbo].[sp_fulltext_database] @action = &#8216;enable&#8217;<br />
end<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET ANSI_NULL_DEFAULT OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET ANSI_NULLS OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET ANSI_PADDING OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET ANSI_WARNINGS OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET ARITHABORT OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET AUTO_CLOSE OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET AUTO_CREATE_STATISTICS ON<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET AUTO_SHRINK OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET AUTO_UPDATE_STATISTICS ON<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET CURSOR_CLOSE_ON_COMMIT OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET CURSOR_DEFAULT  GLOBAL<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET CONCAT_NULL_YIELDS_NULL OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET NUMERIC_ROUNDABORT OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET QUOTED_IDENTIFIER OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET RECURSIVE_TRIGGERS OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET  DISABLE_BROKER<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET AUTO_UPDATE_STATISTICS_ASYNC OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET DATE_CORRELATION_OPTIMIZATION OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET TRUSTWORTHY OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET ALLOW_SNAPSHOT_ISOLATION OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET PARAMETERIZATION SIMPLE<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET READ_COMMITTED_SNAPSHOT OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET HONOR_BROKER_PRIORITY OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET RECOVERY FULL<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET  MULTI_USER<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET PAGE_VERIFY CHECKSUM<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET DB_CHAINING OFF<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET FILESTREAM( NON_TRANSACTED_ACCESS = OFF )<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET TARGET_RECOVERY_TIME = 0 SECONDS<br />
GO</p>
<p>ALTER DATABASE [TrialsDB] SET  READ_WRITE<br />
GO<br />
[/sql]</p>
<p>Now we will create a table 🙂</p>
<p><strong>Create table in database</strong></p>
<p>Below is the query to create table in database.</p>
<p>[sql]<br />
USE [TrialsDB]<br />
GO</p>
<p>/****** Object:  Table [dbo].[tblTags]    Script Date: 17-Feb-16 10:22:00 PM ******/<br />
SET ANSI_NULLS ON<br />
GO</p>
<p>SET QUOTED_IDENTIFIER ON<br />
GO</p>
<p>CREATE TABLE [dbo].[tblTags](<br />
	[tagId] [int] IDENTITY(1,1) NOT NULL,<br />
	[tagName] [nvarchar](50) NOT NULL,<br />
	[tagDescription] [nvarchar](max) NULL,<br />
 CONSTRAINT [PK_tblTags] PRIMARY KEY CLUSTERED<br />
(<br />
	[tagId] ASC<br />
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]<br />
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]</p>
<p>GO<br />
[/sql]</p>
<p>Can we insert some data to the table now?</p>
<p><strong>Insert data to table</strong></p>
<p>You can use the below query to insert the data.</p>
<p>[sql]<br />
USE [TrialsDB]<br />
GO</p>
<p>INSERT INTO [dbo].[tblTags]<br />
           ([tagName]<br />
           ,[tagDescription])<br />
     VALUES<br />
           (&lt;tagName, nvarchar(50),&gt;<br />
           ,&lt;tagDescription, nvarchar(max),&gt;)<br />
GO<br />
[/sql]</p>
<p>So let us say, we have inserted the data as follows.</p>
<p><div id="attachment_11248" style="width: 660px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/02/Insertion_In_Table-e1455728194631.png"><img decoding="async" aria-describedby="caption-attachment-11248" src="http://sibeeshpassion.com/wp-content/uploads/2016/02/Insertion_In_Table-e1455728194631.png" alt="Insertion_In_Table" width="650" height="176" class="size-full wp-image-11248" srcset="/wp-content/uploads/2016/02/Insertion_In_Table-e1455728194631.png 650w, /wp-content/uploads/2016/02/Insertion_In_Table-e1455728194631-300x81.png 300w, /wp-content/uploads/2016/02/Insertion_In_Table-e1455728194631-400x108.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><p id="caption-attachment-11248" class="wp-caption-text">Insertion_In_Table</p></div></p>
<p>Next thing we are going to do is creating a ADO.NET Entity Data Model. </p>
<p><strong>Create Entity Data Model</strong></p>
<p>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. </p>
<p><div id="attachment_11249" style="width: 339px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/02/ADO_NET_Model_Entity.png"><img decoding="async" aria-describedby="caption-attachment-11249" src="http://sibeeshpassion.com/wp-content/uploads/2016/02/ADO_NET_Model_Entity.png" alt="ADO_NET_Model_Entity" width="329" height="207" class="size-full wp-image-11249" srcset="/wp-content/uploads/2016/02/ADO_NET_Model_Entity.png 329w, /wp-content/uploads/2016/02/ADO_NET_Model_Entity-300x189.png 300w" sizes="(max-width: 329px) 100vw, 329px" /></a><p id="caption-attachment-11249" class="wp-caption-text">ADO_NET_Model_Entity</p></div></p>
<p>Then it is time to go back our Web API controller. Please change the code as below.</p>
<p>[csharp]<br />
using System;<br />
using System.Collections.Generic;<br />
using System.Data;<br />
using System.Data.Entity;<br />
using System.Data.Entity.Infrastructure;<br />
using System.Linq;<br />
using System.Net;<br />
using System.Net.Http;<br />
using System.Web;<br />
using System.Web.Http;<br />
using Load_Tags_From_DB_Using_Angular_JS_In_MVC.Models;</p>
<p>namespace Load_Tags_From_DB_Using_Angular_JS_In_MVC.Controllers<br />
{<br />
    public class TagController : ApiController<br />
    {<br />
        private DBEntities db = new DBEntities();</p>
<p>        // GET api/Tag<br />
        public IEnumerable&lt;tblTag&gt; Get()<br />
        {<br />
            return db.tblTags.AsEnumerable();<br />
        }<br />
    }<br />
}<br />
[/csharp]</p>
<p>Once this is done, we can say that we are finished with all steps. That&#8217;s fantastic right? Now we will see the output.</p>
<p><strong>Output</strong></p>
<p><div id="attachment_11250" style="width: 563px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/02/Load_Tags_From_Database_Output.png"><img decoding="async" aria-describedby="caption-attachment-11250" src="http://sibeeshpassion.com/wp-content/uploads/2016/02/Load_Tags_From_Database_Output.png" alt="Load_Tags_From_Database_Output" width="553" height="146" class="size-full wp-image-11250" srcset="/wp-content/uploads/2016/02/Load_Tags_From_Database_Output.png 553w, /wp-content/uploads/2016/02/Load_Tags_From_Database_Output-300x79.png 300w, /wp-content/uploads/2016/02/Load_Tags_From_Database_Output-400x106.png 400w" sizes="(max-width: 553px) 100vw, 553px" /></a><p id="caption-attachment-11250" class="wp-caption-text">Load_Tags_From_Database_Output</p></div></p>
<p>Have a happy coding.</p>
<p><strong>Conclusion</strong></p>
<p>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.</p>
<p><strong>Your turn. What do you think?</strong></p>
<p>A blog isn&#8217;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.</p>
<p>Kindest Regards<br />
Sibeesh Venu</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.sibeeshpassion.com/tagit-control-with-data-from-database-using-angular-js-in-mvc-web-api/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>jQuery Datatable With Server Side Data</title>
		<link>https://www.sibeeshpassion.com/jquery-datatable-with-server-side-data-2/</link>
					<comments>https://www.sibeeshpassion.com/jquery-datatable-with-server-side-data-2/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Thu, 25 Feb 2016 00:00:43 +0000</pubDate>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Angular]]></category>
		<category><![CDATA[Web API]]></category>
		<category><![CDATA[Angular JS]]></category>
		<category><![CDATA[Asp.Net]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Datatable With Server Side]]></category>
		<category><![CDATA[JQuery]]></category>
		<category><![CDATA[jQuery Datatables]]></category>
		<category><![CDATA[MVC]]></category>
		<guid isPermaLink="false">http://sibeecst_passion.com/?p=11266</guid>

					<description><![CDATA[Introduction In this article, we will learn how we can work with jQuery Datatables with server-side data. Here we are going to use an MVC application with jQuery and other required packages installed in it. If you are new to MVC, You can always get the tips/tricks/blogs about that here MVC Tips, Tricks, Blogs. jQuery Datatables is a client-side grid control that is lightweight and easy to use. But when it comes to grid control, it must be usable when it supports the server-side loading of data. This control is perfect for that. I guess, it is enough for the [&#8230;]]]></description>
										<content:encoded><![CDATA[
<h2 class="wp-block-heading">Introduction</h2>



<p>In this article, we will learn how we can work with jQuery Datatables with server-side data. Here we are going to use an MVC application with jQuery and other required packages installed in it. If you are new to MVC, You can always get the tips/tricks/blogs about that here MVC Tips, Tricks, Blogs. jQuery Datatables is a client-side grid control that is lightweight and easy to use. But when it comes to grid control, it must be usable when it supports the server-side loading of data. This control is perfect for that. I guess, it is enough for the introduction. Now we will start using our grid. I hope you will like this.</p>



<h2 class="wp-block-heading"><strong>Download the source code</strong></h2>



<p>You can always download the source code here:</p>



<ul class="wp-block-list"><li><a href="https://github.com/SibeeshVenu/jQuery-Datatable-With-Server-Side-Data" target="_blank" rel="noreferrer noopener">Datatable With Server-Side Data</a></li></ul>



<h2 class="wp-block-heading"><strong>Create a MVC application</strong></h2>



<p>Click File-&gt; New-&gt; 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.</p>



<ul class="wp-block-list"><li>Datatables Package</li><li>jQuery</li></ul>



<p>You can all the items mentioned above from NuGet. Right-click on your project name and select Manage NuGet packages.</p>



<figure class="wp-block-image alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/02/Manage-NuGet-Package-Window-e1455700665396.png"><img decoding="async" width="650" height="432" src="http://sibeeshpassion.com/wp-content/uploads/2016/02/Manage-NuGet-Package-Window-e1455700665396.png" alt="Manage NuGet Package Window" class="wp-image-11235" srcset="/wp-content/uploads/2016/02/Manage-NuGet-Package-Window-e1455700665396.png 650w, /wp-content/uploads/2016/02/Manage-NuGet-Package-Window-e1455700665396-300x199.png 300w, /wp-content/uploads/2016/02/Manage-NuGet-Package-Window-e1455700665396-400x266.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><figcaption>Manage NuGet Package Window</figcaption></figure>



<p>Once you have installed those items, please make sure that all the items(jQuery, Datatables JS files) are loaded in your scripts folder.</p>



<h2 class="wp-block-heading"><strong>Using the code</strong></h2>



<p>Now let us add the needed references.</p>



<h3 class="wp-block-heading">Include the references in your _Layout.cshtml</h3>



<p>As we have already installed all the packages we need, now we need to add the references, right? After adding the reference, your _Layout.cshtml will looks like below.</p>



<script src="https://gist.github.com/SibeeshVenu/4b71315abf732ca3a929e8750cf13638.js"></script>



<p>Here <em>MyScripts.js</em> is the JavaScript file where we are going to write our own scripts.</p>



<p><em>Add a normal MVC controller</em></p>



<p>Now we will add a normal MVC controller in our app. Once you add that you can see an ActionResult is created for us.</p>



<p><code>public ActionResult Index()<br>{<br>return View();<br>}</code></p>



<p>Right-click on the controller, and click add view, that will create a View for you. Now we will change the view as follows. </p>



<script src="https://gist.github.com/SibeeshVenu/87fa8feefb4bd7fcb9fbc867d8a23921.js"></script>



<p>So we have set the headers and footer for our grid, where we are going to load the grid control in the table <em>myGrid</em>. So far the UI part is done, now it is time to set up our database and entity model. Are you ready?</p>



<h3 class="wp-block-heading"><strong>Create a database</strong></h3>



<p>The following query can be used to create a database in your SQL Server.</p>



<script src="https://gist.github.com/SibeeshVenu/5bf2b19e004f619ebfb1f9e6229ef66b.js"></script>



<p>Now we will create a table 🙂</p>



<h3 class="wp-block-heading"><strong>Create table in database</strong></h3>



<p>Below is the query to create table in database.</p>



<script src="https://gist.github.com/SibeeshVenu/8b4797ecfbcfe5841f9ca85a5ef131c8.js"></script>



<h3 class="wp-block-heading"><strong>Insert data to table</strong></h3>



<p>To insert the data, I will attach a database script file along with the download file, you can either run that or insert some data by using the below query. By the way, if you would like to know how to generate scripts with data in SQL Server, you can check <a rel="noopener noreferrer" href="http://sibeeshpassion.com/generate-database-scripts-with-data-in-sql-server/" target="_blank">here</a>.</p>



<script src="https://gist.github.com/SibeeshVenu/9ad0fcd0e2220a4b2a93d7617716416a.js"></script>



<p>Along with this, we can create a new stored procedure that will fetch the data. Following is the query to create the stored procedure.</p>



<script src="https://gist.github.com/SibeeshVenu/40e2e26f6dd93dbac671fc9c33743ccd.js"></script>



<p>Next thing we are going to do is creating a ADO.NET Entity Data Model.</p>



<h3 class="wp-block-heading"><strong>Create Entity Data Model</strong></h3>



<p>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.</p>



<p>Now we will go back to our controller and add a new JsonResult which can be called via a new jQuery Ajax request. No worries, we will create that Ajax requests later. Once you add the Jsonresult action, I hope your controller will look like this.</p>



<script src="https://gist.github.com/SibeeshVenu/344693e90203b925d34b755e83a2ec8a.js"></script>



<p>Here <em>TrialsDBEntities </em>is our entity class. Please be noted that to use the model classes in your controller, you must add the reference as follows.</p>



<p><code>using jQuery_Datatable_With_Server_Side_Data.Models;</code></p>



<p>I know all you are familiar with this, I am just saying!. Now can we create a function <em>GetSales</em> in our model class <em>Sales </em>?.</p>



<script src="https://gist.github.com/SibeeshVenu/b7b4a55890e969fe518cd30cd24433fb.js"></script>



<p>We uses normal LINQ queries here, and we take only 100 records to load for now. If you don&#8217;t want to use this method you can call our stored procedure which we have created while creating our database. You can call this as explained in the below function.</p>



<script src="https://gist.github.com/SibeeshVenu/f189bb513e93566d140429b4a9836834.js"></script>



<p>Now the only thing pending is to call our controller JsonResult action right? We will do some code in our MyScript.js file.</p>



<script src="https://gist.github.com/SibeeshVenu/5093c34f6a455a758426ac8df2b00118.js"></script>



<p>Here <em>&#8220;dataSrc&#8221;: &#8220;&#8221; </em> should be used if you have a plain <a rel="noopener noreferrer" href="http://sibeeshpassion.com/tag/json/" target="_blank">JSON </a>data. The sample data can be find below.</p>



<script src="https://gist.github.com/SibeeshVenu/a2ae9ec5f56a05ef62f6f911e4918ba3.js"></script>



<p>We have done everything!. Can we see the output now?</p>



<h2 class="wp-block-heading"><strong>Output</strong></h2>



<figure class="wp-block-image alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/02/jQuery-Datatable-With-Server-Side-Data.png"><img decoding="async" width="1024" height="596" src="http://sibeeshpassion.com/wp-content/uploads/2016/02/jQuery-Datatable-With-Server-Side-Data-1024x596.png" alt="jQuery Datatable With Server Side Data" class="wp-image-11267" srcset="/wp-content/uploads/2016/02/jQuery-Datatable-With-Server-Side-Data-1024x596.png 1024w, /wp-content/uploads/2016/02/jQuery-Datatable-With-Server-Side-Data-300x175.png 300w, /wp-content/uploads/2016/02/jQuery-Datatable-With-Server-Side-Data-768x447.png 768w, /wp-content/uploads/2016/02/jQuery-Datatable-With-Server-Side-Data-400x233.png 400w, /wp-content/uploads/2016/02/jQuery-Datatable-With-Server-Side-Data-1030x600.png 1030w, /wp-content/uploads/2016/02/jQuery-Datatable-With-Server-Side-Data.png 1097w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption>jQuery Datatable With Server Side Data</figcaption></figure>



<figure class="wp-block-image alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/02/jQuery-Datatable-With-Server-Side-Data-Search.png"><img decoding="async" width="1024" height="379" src="http://sibeeshpassion.com/wp-content/uploads/2016/02/jQuery-Datatable-With-Server-Side-Data-Search-1024x379.png" alt="jQuery Datatable With Server Side Data Search" class="wp-image-11268" srcset="/wp-content/uploads/2016/02/jQuery-Datatable-With-Server-Side-Data-Search-1024x379.png 1024w, /wp-content/uploads/2016/02/jQuery-Datatable-With-Server-Side-Data-Search-300x111.png 300w, /wp-content/uploads/2016/02/jQuery-Datatable-With-Server-Side-Data-Search-768x284.png 768w, /wp-content/uploads/2016/02/jQuery-Datatable-With-Server-Side-Data-Search-400x148.png 400w, /wp-content/uploads/2016/02/jQuery-Datatable-With-Server-Side-Data-Search.png 1109w" sizes="(max-width: 1024px) 100vw, 1024px" /></a><figcaption>jQuery Datatable With Server Side Data Search</figcaption></figure>



<p>Have a happy coding.</p>



<h2 class="wp-block-heading"><strong>Conclusion</strong></h2>



<p>Did I miss anything that you may think which is needed? Did you use jQuery Datatables in your application? 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.</p>



<h2 class="wp-block-heading"><strong>Your turn. What do you think?</strong></h2>



<p>A blog isn&#8217;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.</p>



<p>Kindest Regards<br>Sibeesh Venu</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.sibeeshpassion.com/jquery-datatable-with-server-side-data-2/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Web API With Angular JS</title>
		<link>https://www.sibeeshpassion.com/web-api-with-angular-js-3/</link>
					<comments>https://www.sibeeshpassion.com/web-api-with-angular-js-3/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Thu, 11 Feb 2016 00:00:23 +0000</pubDate>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Angular]]></category>
		<category><![CDATA[Web API]]></category>
		<category><![CDATA[Angular JS]]></category>
		<category><![CDATA[Angular JS Controller]]></category>
		<category><![CDATA[Angular JS Module]]></category>
		<category><![CDATA[Angular JS Service]]></category>
		<category><![CDATA[contenteditable]]></category>
		<category><![CDATA[MVC]]></category>
		<guid isPermaLink="false">http://sibeecst_passion.com/?p=11185</guid>

					<description><![CDATA[[toc] Introduction In this article, we will learn about CRUD operations in Web API using Angular JS. We will use Visual Studio 2015 to create a Web API and performs the operations. In this project, we are going to create a database and table called tbl_Subcribers which actually contains a list of data. Here we will use Angular JS for all of our client side operations. If you are new to Web API, please read how to retrieve the data from database using Web API here. I am going to explain the complete process in a step by step manner. [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>[toc]</p>
<h2>Introduction</h2>
<p>In this article, we will learn about CRUD operations in Web API using Angular JS. We will use <a href="http://sibeeshpassion.com/tag/visual-studio/" target="_blank" rel="noopener">Visual Studio</a> 2015 to create a Web API and performs the operations. In this project, we are going to create a database and table called <em>tbl_Subcribers</em> which actually contains a list of data. Here we will use Angular JS for all of our client side operations. If you are new to Web API, please read how to retrieve the data from database using Web API <a href="http://sibeeshpassion.com/load-data-from-database-using-web-api/" target="_blank" rel="noopener">here</a>. I am going to explain the complete process in a step by step manner. I hope you will like this.</p>
<h2><strong>Download the source code</strong></h2>
<p>You can always download the source code here: <a href="https://gallery.technet.microsoft.com/Web-API-With-Angular-JS-8f4ac03d" target="_blank" rel="noopener">Web API and Angular JS</a></p>
<h2><strong>Background</strong></h2>
<p>Yesterday I have got a call from one of my follower. He asked me about Web API, I have explained to him what are all the things I know about the Web API. But he was not convinced with the information I shared through the phone. At last, he asked me to write an article about Web API in a simple manner. So I agreed to do the same. Here I am dedicating this article to him. I hope he can find this useful.</p>
<h3><em>What is a Web API?</em></h3>
<p>A Web API is a kind of a framework which makes building HTTP services easier than ever. It can be used almost everywhere including a wide range of clients, mobile devices, browsers etc. It contains normal MVC features like Model, Controller, Actions, Routing etc. Support all HTTP verbs like POST, GET, DELETE, PUT.</p>
<p><div id="attachment_10874" style="width: 560px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2015/10/Why-Web-API.png"><img decoding="async" aria-describedby="caption-attachment-10874" class="size-full wp-image-10874" src="http://sibeeshpassion.com/wp-content/uploads/2015/10/Why-Web-API.png" alt="Why Web API" width="550" height="377" srcset="/wp-content/uploads/2015/10/Why-Web-API.png 550w, /wp-content/uploads/2015/10/Why-Web-API-300x206.png 300w, /wp-content/uploads/2015/10/Why-Web-API-320x218.png 320w, /wp-content/uploads/2015/10/Why-Web-API-160x110.png 160w, /wp-content/uploads/2015/10/Why-Web-API-400x274.png 400w" sizes="(max-width: 550px) 100vw, 550px" /></a><p id="caption-attachment-10874" class="wp-caption-text">Why Web API</p></div></p>
<p><em>Image Courtesy : blogs.msdn.com</em></p>
<p><div id="attachment_10875" style="width: 660px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2015/10/Why-Web-API1-e1446290457816.png"><img decoding="async" aria-describedby="caption-attachment-10875" class="size-full wp-image-10875" src="http://sibeeshpassion.com/wp-content/uploads/2015/10/Why-Web-API1-e1446290457816.png" alt="Why Web API" width="650" height="454" srcset="/wp-content/uploads/2015/10/Why-Web-API1-e1446290457816.png 650w, /wp-content/uploads/2015/10/Why-Web-API1-e1446290457816-300x210.png 300w, /wp-content/uploads/2015/10/Why-Web-API1-e1446290457816-400x279.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><p id="caption-attachment-10875" class="wp-caption-text">Why Web API</p></div></p>
<p><em>Image Courtesy : forums.asp.net</em></p>
<h2><strong>Using the code</strong></h2>
<h3>Creating project</h3>
<p>We will create our project in Visual Studio 2015. To create a project click File-&gt; New-&gt; Project. And select Web API as a template.</p>
<p><div id="attachment_11189" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/02/Web-API-Template-e1454769881232.png"><img decoding="async" aria-describedby="caption-attachment-11189" class="size-large wp-image-11189" src="http://sibeeshpassion.com/wp-content/uploads/2016/02/Web-API-Template-1024x576.png" alt="Web API Template" width="634" height="357" /></a><p id="caption-attachment-11189" class="wp-caption-text">Web API Template</p></div></p>
<p>Once you have created a new project, your solution explorer will look like this.</p>
<p><div id="attachment_11186" style="width: 430px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/02/Web-API-With-Angular-JS-Solution-Explorer.png"><img decoding="async" aria-describedby="caption-attachment-11186" class="size-full wp-image-11186" src="http://sibeeshpassion.com/wp-content/uploads/2016/02/Web-API-With-Angular-JS-Solution-Explorer.png" alt="Web API With Angular JS Solution Explorer " width="420" height="672" srcset="/wp-content/uploads/2016/02/Web-API-With-Angular-JS-Solution-Explorer.png 420w, /wp-content/uploads/2016/02/Web-API-With-Angular-JS-Solution-Explorer-188x300.png 188w, /wp-content/uploads/2016/02/Web-API-With-Angular-JS-Solution-Explorer-400x640.png 400w, /wp-content/uploads/2016/02/Web-API-With-Angular-JS-Solution-Explorer-375x600.png 375w" sizes="(max-width: 420px) 100vw, 420px" /></a><p id="caption-attachment-11186" class="wp-caption-text">Web API With Angular JS Solution Explorer</p></div></p>
<p>As I said, we are going to use Angular JS for all of our client side operations. So the next thing we need to do is, installing the Angular JS from NuGet packages.</p>
<p><div id="attachment_11188" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/02/Installing-Angular-JS-e1454769674992.png"><img decoding="async" aria-describedby="caption-attachment-11188" class="size-large wp-image-11188" src="http://sibeeshpassion.com/wp-content/uploads/2016/02/Installing-Angular-JS-1024x576.png" alt="Installing Angular JS" width="634" height="357" /></a><p id="caption-attachment-11188" class="wp-caption-text">Installing Angular JS</p></div></p>
<h3><strong>Install Angular JS</strong></h3>
<p>Now we will create a control in our project.</p>
<p><div id="attachment_10171" style="width: 662px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2015/08/CRUD_in_MVC_Using_Web_API_Adding_Control.png"><img decoding="async" aria-describedby="caption-attachment-10171" class="size-full wp-image-10171" src="http://sibeeshpassion.com/wp-content/uploads/2015/08/CRUD_in_MVC_Using_Web_API_Adding_Control.png" alt="CRUD_in_MVC_Using_Web_API_Adding_Control" width="652" height="596" srcset="/wp-content/uploads/2015/08/CRUD_in_MVC_Using_Web_API_Adding_Control.png 652w, /wp-content/uploads/2015/08/CRUD_in_MVC_Using_Web_API_Adding_Control-300x274.png 300w, /wp-content/uploads/2015/08/CRUD_in_MVC_Using_Web_API_Adding_Control-400x366.png 400w" sizes="(max-width: 652px) 100vw, 652px" /></a><p id="caption-attachment-10171" class="wp-caption-text">CRUD_in_MVC_Using_Web_API_Adding_Control</p></div></p>
<p>Now will create a database. Here I am using SQL Server Management Studio With SQL Server Express.</p>
<h3><strong>Create Database</strong></h3>
<p>Below is the query to create a database.</p>
<p>[sql]<br />
USE [master]<br />
GO</p>
<p>/****** Object: Database [sibeeshpassion] Script Date: 06-02-2016 08:18:42 PM ******/<br />
CREATE DATABASE [sibeeshpassion]<br />
CONTAINMENT = NONE<br />
ON PRIMARY<br />
( NAME = N&#8217;sibeeshpassion&#8217;, FILENAME = N&#8217;C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\DATA\sibeeshpassion.mdf&#8217; , SIZE = 5120KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )<br />
LOG ON<br />
( NAME = N&#8217;sibeeshpassion_log&#8217;, FILENAME = N&#8217;C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\DATA\sibeeshpassion_log.ldf&#8217; , SIZE = 2048KB , MAXSIZE = 2048GB , FILEGROWTH = 10%)<br />
GO</p>
<p>ALTER DATABASE [sibeeshpassion] SET COMPATIBILITY_LEVEL = 120<br />
GO</p>
<p>IF (1 = FULLTEXTSERVICEPROPERTY(&#8216;IsFullTextInstalled&#8217;))<br />
begin<br />
EXEC [sibeeshpassion].[dbo].[sp_fulltext_database] @action = &#8216;enable&#8217;<br />
end<br />
GO</p>
<p>ALTER DATABASE [sibeeshpassion] SET ANSI_NULL_DEFAULT OFF<br />
GO</p>
<p>ALTER DATABASE [sibeeshpassion] SET ANSI_NULLS OFF<br />
GO</p>
<p>ALTER DATABASE [sibeeshpassion] SET ANSI_PADDING OFF<br />
GO</p>
<p>ALTER DATABASE [sibeeshpassion] SET ANSI_WARNINGS OFF<br />
GO</p>
<p>ALTER DATABASE [sibeeshpassion] SET ARITHABORT OFF<br />
GO</p>
<p>ALTER DATABASE [sibeeshpassion] SET AUTO_CLOSE OFF<br />
GO</p>
<p>ALTER DATABASE [sibeeshpassion] SET AUTO_SHRINK OFF<br />
GO</p>
<p>ALTER DATABASE [sibeeshpassion] SET AUTO_UPDATE_STATISTICS ON<br />
GO</p>
<p>ALTER DATABASE [sibeeshpassion] SET CURSOR_CLOSE_ON_COMMIT OFF<br />
GO</p>
<p>ALTER DATABASE [sibeeshpassion] SET CURSOR_DEFAULT GLOBAL<br />
GO</p>
<p>ALTER DATABASE [sibeeshpassion] SET CONCAT_NULL_YIELDS_NULL OFF<br />
GO</p>
<p>ALTER DATABASE [sibeeshpassion] SET NUMERIC_ROUNDABORT OFF<br />
GO</p>
<p>ALTER DATABASE [sibeeshpassion] SET QUOTED_IDENTIFIER OFF<br />
GO</p>
<p>ALTER DATABASE [sibeeshpassion] SET RECURSIVE_TRIGGERS OFF<br />
GO</p>
<p>ALTER DATABASE [sibeeshpassion] SET DISABLE_BROKER<br />
GO</p>
<p>ALTER DATABASE [sibeeshpassion] SET AUTO_UPDATE_STATISTICS_ASYNC OFF<br />
GO</p>
<p>ALTER DATABASE [sibeeshpassion] SET DATE_CORRELATION_OPTIMIZATION OFF<br />
GO</p>
<p>ALTER DATABASE [sibeeshpassion] SET TRUSTWORTHY OFF<br />
GO</p>
<p>ALTER DATABASE [sibeeshpassion] SET ALLOW_SNAPSHOT_ISOLATION OFF<br />
GO</p>
<p>ALTER DATABASE [sibeeshpassion] SET PARAMETERIZATION SIMPLE<br />
GO</p>
<p>ALTER DATABASE [sibeeshpassion] SET READ_COMMITTED_SNAPSHOT OFF<br />
GO</p>
<p>ALTER DATABASE [sibeeshpassion] SET HONOR_BROKER_PRIORITY OFF<br />
GO</p>
<p>ALTER DATABASE [sibeeshpassion] SET RECOVERY SIMPLE<br />
GO</p>
<p>ALTER DATABASE [sibeeshpassion] SET MULTI_USER<br />
GO</p>
<p>ALTER DATABASE [sibeeshpassion] SET PAGE_VERIFY CHECKSUM<br />
GO</p>
<p>ALTER DATABASE [sibeeshpassion] SET DB_CHAINING OFF<br />
GO</p>
<p>ALTER DATABASE [sibeeshpassion] SET FILESTREAM( NON_TRANSACTED_ACCESS = OFF )<br />
GO</p>
<p>ALTER DATABASE [sibeeshpassion] SET TARGET_RECOVERY_TIME = 0 SECONDS<br />
GO</p>
<p>ALTER DATABASE [sibeeshpassion] SET DELAYED_DURABILITY = DISABLED<br />
GO</p>
<p>ALTER DATABASE [sibeeshpassion] SET READ_WRITE<br />
GO<br />
[/sql]</p>
<p>Now we can create a table and insert few data into it.</p>
<h3><strong>Create table in database</strong></h3>
<p>Below is the query to create table in database.</p>
<p>[sql]<br />
USE [sibeeshpassion]<br />
GO</p>
<p>/****** Object: Table [dbo].[tbl_Subscribers] Script Date: 06-02-2016 08:21:06 PM ******/<br />
SET ANSI_NULLS ON<br />
GO</p>
<p>SET QUOTED_IDENTIFIER ON<br />
GO</p>
<p>CREATE TABLE [dbo].[tbl_Subscribers](<br />
[SubscriberID] [int] NOT NULL,<br />
[MailID] [nvarchar](50) NOT NULL,<br />
[SubscribedDate] [datetime2](7) NOT NULL,<br />
PRIMARY KEY CLUSTERED<br />
(<br />
[SubscriberID] ASC<br />
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]<br />
) ON [PRIMARY]</p>
<p>GO<br />
[/sql]</p>
<h3><strong>Insert data to table</strong></h3>
<p>[sql]<br />
INSERT INTO [dbo].[tbl_Subscribers] ([SubscriberID], [MailID], [SubscribedDate]) VALUES (1, N&#8217;sibikv4u@gmail.com&#8217;, N&#8217;2015-10-30 00:00:00&#8242;)<br />
INSERT INTO [dbo].[tbl_Subscribers] ([SubscriberID], [MailID], [SubscribedDate]) VALUES (2, N&#8217;sibeesh.venu@gmail.com&#8217;, N&#8217;2015-10-29 00:00:00&#8242;)<br />
INSERT INTO [dbo].[tbl_Subscribers] ([SubscriberID], [MailID], [SubscribedDate]) VALUES (3, N&#8217;ajaybhasy@gmail.com&#8217;, N&#8217;2015-10-28 00:00:00&#8242;)<br />
[/sql]</p>
<p>Our database seems to be ready now. Then we can go ahead and create entity in our project.</p>
<h3><strong>Creating entity model</strong></h3>
<p>To create an entity, please follows the steps shows in the below images.</p>
<p><div id="attachment_11190" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/02/Creting-Entity-Model-1-e1454770826847.png"><img decoding="async" aria-describedby="caption-attachment-11190" class="size-large wp-image-11190" src="http://sibeeshpassion.com/wp-content/uploads/2016/02/Creting-Entity-Model-1-1024x576.png" alt="Creating Entity Model 1" width="634" height="357" /></a><p id="caption-attachment-11190" class="wp-caption-text">Creating Entity Model 1</p></div></p>
<p><div id="attachment_11191" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/02/Creting-Entity-Model-2.png"><img decoding="async" aria-describedby="caption-attachment-11191" class="size-large wp-image-11191" src="http://sibeeshpassion.com/wp-content/uploads/2016/02/Creting-Entity-Model-2-1024x576.png" alt="Creating Entity Model 2" width="634" height="357" srcset="/wp-content/uploads/2016/02/Creting-Entity-Model-2-1024x576.png 1024w, /wp-content/uploads/2016/02/Creting-Entity-Model-2-300x169.png 300w, /wp-content/uploads/2016/02/Creting-Entity-Model-2-768x432.png 768w, /wp-content/uploads/2016/02/Creting-Entity-Model-2-400x225.png 400w, /wp-content/uploads/2016/02/Creting-Entity-Model-2-1067x600.png 1067w, /wp-content/uploads/2016/02/Creting-Entity-Model-2.png 1920w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-11191" class="wp-caption-text">Creating Entity Model 2</p></div></p>
<p><div id="attachment_11192" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/02/Creting-Entity-Model-3.png"><img decoding="async" aria-describedby="caption-attachment-11192" class="size-large wp-image-11192" src="http://sibeeshpassion.com/wp-content/uploads/2016/02/Creting-Entity-Model-3-1024x576.png" alt="Creating Entity Model 3" width="634" height="357" srcset="/wp-content/uploads/2016/02/Creting-Entity-Model-3-1024x576.png 1024w, /wp-content/uploads/2016/02/Creting-Entity-Model-3-300x169.png 300w, /wp-content/uploads/2016/02/Creting-Entity-Model-3-768x432.png 768w, /wp-content/uploads/2016/02/Creting-Entity-Model-3-400x225.png 400w, /wp-content/uploads/2016/02/Creting-Entity-Model-3-1067x600.png 1067w, /wp-content/uploads/2016/02/Creting-Entity-Model-3.png 1920w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-11192" class="wp-caption-text">Creating Entity Model 3</p></div></p>
<p><div id="attachment_11193" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/02/Creting-Entity-Model-4.png"><img decoding="async" aria-describedby="caption-attachment-11193" class="size-large wp-image-11193" src="http://sibeeshpassion.com/wp-content/uploads/2016/02/Creting-Entity-Model-4-1024x576.png" alt="Creating Entity Model 4" width="634" height="357" srcset="/wp-content/uploads/2016/02/Creting-Entity-Model-4-1024x576.png 1024w, /wp-content/uploads/2016/02/Creting-Entity-Model-4-300x169.png 300w, /wp-content/uploads/2016/02/Creting-Entity-Model-4-768x432.png 768w, /wp-content/uploads/2016/02/Creting-Entity-Model-4-400x225.png 400w, /wp-content/uploads/2016/02/Creting-Entity-Model-4-1067x600.png 1067w, /wp-content/uploads/2016/02/Creting-Entity-Model-4.png 1920w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-11193" class="wp-caption-text">Creating Entity Model 4</p></div></p>
<p><div id="attachment_11194" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/02/Creting-Entity-Model-5.png"><img decoding="async" aria-describedby="caption-attachment-11194" class="size-large wp-image-11194" src="http://sibeeshpassion.com/wp-content/uploads/2016/02/Creting-Entity-Model-5-1024x576.png" alt="Creating Entity Model 5" width="634" height="357" srcset="/wp-content/uploads/2016/02/Creting-Entity-Model-5-1024x576.png 1024w, /wp-content/uploads/2016/02/Creting-Entity-Model-5-300x169.png 300w, /wp-content/uploads/2016/02/Creting-Entity-Model-5-768x432.png 768w, /wp-content/uploads/2016/02/Creting-Entity-Model-5-400x225.png 400w, /wp-content/uploads/2016/02/Creting-Entity-Model-5-1067x600.png 1067w, /wp-content/uploads/2016/02/Creting-Entity-Model-5.png 1920w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-11194" class="wp-caption-text">Creating Entity Model 5</p></div></p>
<p><div id="attachment_11195" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/02/Creting-Entity-Model-6.png"><img decoding="async" aria-describedby="caption-attachment-11195" class="size-large wp-image-11195" src="http://sibeeshpassion.com/wp-content/uploads/2016/02/Creting-Entity-Model-6-1024x576.png" alt="Creating Entity Model 6" width="634" height="357" srcset="/wp-content/uploads/2016/02/Creting-Entity-Model-6-1024x576.png 1024w, /wp-content/uploads/2016/02/Creting-Entity-Model-6-300x169.png 300w, /wp-content/uploads/2016/02/Creting-Entity-Model-6-768x432.png 768w, /wp-content/uploads/2016/02/Creting-Entity-Model-6-400x225.png 400w, /wp-content/uploads/2016/02/Creting-Entity-Model-6-1067x600.png 1067w, /wp-content/uploads/2016/02/Creting-Entity-Model-6.png 1920w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-11195" class="wp-caption-text">Creating Entity Model 6</p></div></p>
<p>Now it is time to create a API controller.</p>
<p>Select <em>Empty API Controller</em> as template.</p>
<p><div id="attachment_11196" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/02/Web-API-Contoller-With-Actions.png"><img decoding="async" aria-describedby="caption-attachment-11196" class="size-large wp-image-11196" src="http://sibeeshpassion.com/wp-content/uploads/2016/02/Web-API-Contoller-With-Actions-1024x713.png" alt="Web API Contoller With Actions" width="634" height="441" srcset="/wp-content/uploads/2016/02/Web-API-Contoller-With-Actions-1024x713.png 1024w, /wp-content/uploads/2016/02/Web-API-Contoller-With-Actions-300x209.png 300w, /wp-content/uploads/2016/02/Web-API-Contoller-With-Actions-768x535.png 768w, /wp-content/uploads/2016/02/Web-API-Contoller-With-Actions-160x110.png 160w, /wp-content/uploads/2016/02/Web-API-Contoller-With-Actions-400x279.png 400w, /wp-content/uploads/2016/02/Web-API-Contoller-With-Actions-862x600.png 862w, /wp-content/uploads/2016/02/Web-API-Contoller-With-Actions.png 1182w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-11196" class="wp-caption-text">Web API Contoller With Actions</p></div></p>
<h3><strong>Read Operation</strong></h3>
<p>Now you can see some actions are already created for you by default. Cool right? Now as of now we will concentrate only in retrieving the data. So please change the method Get as follows.</p>
<p>[csharp]<br />
public IEnumerable&lt;tbl_Subscribers&gt; Get()<br />
{<br />
return myEntity.tbl_Subscribers.AsEnumerable();<br />
}<br />
[/csharp]</p>
<p>Before the please do not forget to create an instance for your entity.</p>
<p>[csharp]<br />
private sibeeshpassionEntities myEntity = new sibeeshpassionEntities();<br />
[/csharp]</p>
<p>And make sure you have added the needed namespaces with the model.</p>
<p>[csharp]<br />
using System.Data.Entity;<br />
using WebAPIAndAngular.Models;<br />
[/csharp]</p>
<p>As you can notice that we have selected Empty API Controller instead of selecting a normal controller. There are few difference between our normal controller and Empty API Controller.</p>
<h3><strong>Controller VS Empty API Controller</strong></h3>
<p>A controller normally render your views. But an API controller returns the data which is already serialized. A controller action returns JSON() by converting the data. You can get rid of this by using API controller.</p>
<p>Find out more: <a href="http://stackoverflow.com/questions/9494966/difference-between-apicontroller-and-controller-in-asp-net-mvc" target="_blank" rel="noopener">Controller VS API Controller </a></p>
<p>Now our API is ready for action. So it is time to create an another controller and a view. Here I am creating a normal controller with Index view.</p>
<p>Once the view is created, we will created three JS files in the script folder.</p>
<p><div id="attachment_11197" style="width: 366px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/02/Angular-JS-Operation-FIles.png"><img decoding="async" aria-describedby="caption-attachment-11197" class="size-full wp-image-11197" src="http://sibeeshpassion.com/wp-content/uploads/2016/02/Angular-JS-Operation-FIles.png" alt="Angular JS Operation FIles" width="356" height="125" srcset="/wp-content/uploads/2016/02/Angular-JS-Operation-FIles.png 356w, /wp-content/uploads/2016/02/Angular-JS-Operation-FIles-300x105.png 300w" sizes="(max-width: 356px) 100vw, 356px" /></a><p id="caption-attachment-11197" class="wp-caption-text">Angular JS Operation FIles</p></div></p>
<p>Now we will start our Angular JS part. If you are new to Angular JS, I strongly recommend you to check here.<a href="http://sibeeshpassion.com/category/angularjs/" target="_blank" rel="noopener">Angular JS Basics</a></p>
<p>Open the file Module.js and create an app.</p>
<p>[js]<br />
var app;<br />
(function () {<br />
app = angular.module(&#8220;APIModule&#8221;, []);<br />
})();<br />
[/js]</p>
<p>Here APIModule is the name of our module. Check <a href="https://docs.angularjs.org/error/$injector/nomod?p0=APIModule" target="_blank" rel="noopener">here </a>for more information.</p>
<p>Open the file Service.js and create a service as follows.</p>
<p>[js]<br />
app.service(&#8220;APIService&#8221;, function ($http) {<br />
this.getSubs = function () {<br />
return $http.get(&#8220;api/Subscriber&#8221;)<br />
}<br />
});<br />
[/js]</p>
<p>Here APIService is our service name which we will call from our controller. The <em>api/Subscriber</em> will call the Get method in our API controller.</p>
<p><div id="attachment_11198" style="width: 660px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/02/Get-Operation-In-API-Controller-e1454772443988.png"><img decoding="async" aria-describedby="caption-attachment-11198" class="size-full wp-image-11198" src="http://sibeeshpassion.com/wp-content/uploads/2016/02/Get-Operation-In-API-Controller-e1454772443988.png" alt="Get Operation In API Controller" width="650" height="162" srcset="/wp-content/uploads/2016/02/Get-Operation-In-API-Controller-e1454772443988.png 650w, /wp-content/uploads/2016/02/Get-Operation-In-API-Controller-e1454772443988-300x75.png 300w, /wp-content/uploads/2016/02/Get-Operation-In-API-Controller-e1454772443988-400x100.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><p id="caption-attachment-11198" class="wp-caption-text">Get Operation In API Controller</p></div></p>
<p>Now Open our Controller.JS and write code as below.</p>
<p>[js]<br />
app.controller(&#8216;APIController&#8217;, function ($scope, APIService) {<br />
getAll();<br />
function getAll()<br />
{<br />
var servCall = APIService.getSubs();<br />
servCall.then(function (d) {<br />
$scope.subscriber = d.data;<br />
}, function (error) {<br />
$log.error(&#8216;Oops! Something went wrong while fetching the data.&#8217;)<br />
})<br />
}<br />
})<br />
[/js]</p>
<p>We are calling the getSubs function which we created in our service. Once we get the data we are assigning it to the $scope.subscriber, so that we can use it in our view.</p>
<p>Now the angular JS part for retrieving all data is done. Can we do the needed changes in the view now?</p>
<h3><strong>Updating View</strong></h3>
<p>Open the Index.cshtml view and change it as below.</p>
<p>[html]</p>
<p>@{<br />
ViewBag.Title = &#8220;Welcome&#8221;;<br />
}<br />
&lt;style&gt;<br />
table, tr, td, th {<br />
border: 1px solid #ccc;<br />
padding: 10px;<br />
margin: 10px;<br />
}<br />
&lt;/style&gt;</p>
<p>&lt;h2&gt;Welcome to Sibeesh Passion&#8217;s Email List&lt;/h2&gt;<br />
&lt;body data-ng-app=&#8221;APIModule&#8221;&gt;<br />
&lt;div id=&#8221;tblSubs&#8221; ng-controller=&#8221;APIController&#8221;&gt;<br />
&lt;table&gt;<br />
&lt;tr&gt;<br />
&lt;th&gt;ID&lt;/th&gt;<br />
&lt;th&gt;Email ID&lt;/th&gt;<br />
&lt;th&gt;Subscribed Date&lt;/th&gt;<br />
&lt;/tr&gt;<br />
&lt;tbody data-ng-repeat=&#8221;sub in subscriber&#8221;&gt;<br />
&lt;tr&gt;<br />
&lt;td&gt;{{sub.SubscriberID}}&lt;/td&gt;<br />
&lt;td&gt;{{sub.MailID}}&lt;/td&gt;<br />
&lt;td&gt;{{sub.SubscribedDate}}&lt;/td&gt;<br />
&lt;/tr&gt;<br />
&lt;/tbody&gt;<br />
&lt;/table&gt;<br />
&lt;/div&gt;<br />
&lt;/body&gt;<br />
&lt;script src=&#8221;~/Scripts/angular.js&#8221;&gt;&lt;/script&gt;<br />
&lt;script src=&#8221;~/Scripts/angular-route.js&#8221;&gt;&lt;/script&gt;<br />
&lt;script src=&#8221;~/Scripts/APIScripts/Module.js&#8221;&gt;&lt;/script&gt;<br />
&lt;script src=&#8221;~/Scripts/APIScripts/Service.js&#8221;&gt;&lt;/script&gt;<br />
&lt;script src=&#8221;~/Scripts/APIScripts/Controller.js&#8221;&gt;&lt;/script&gt;<br />
[/html]</p>
<p>Please don&#8217;r forget to load the needed scripts. Here we have set body as our data-ng-app and table as our ng-controller. We are looping through the data using data-ng-repeat.</p>
<p>If everything is done, we can build the application and see the output.</p>
<p><div id="attachment_11199" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/02/Wep-API-Get-All-Record.png"><img decoding="async" aria-describedby="caption-attachment-11199" class="size-large wp-image-11199" src="http://sibeeshpassion.com/wp-content/uploads/2016/02/Wep-API-Get-All-Record-1024x576.png" alt="Wep API Get All Record" width="634" height="357" srcset="/wp-content/uploads/2016/02/Wep-API-Get-All-Record-1024x576.png 1024w, /wp-content/uploads/2016/02/Wep-API-Get-All-Record-300x169.png 300w, /wp-content/uploads/2016/02/Wep-API-Get-All-Record-768x432.png 768w, /wp-content/uploads/2016/02/Wep-API-Get-All-Record-400x225.png 400w, /wp-content/uploads/2016/02/Wep-API-Get-All-Record-1067x600.png 1067w, /wp-content/uploads/2016/02/Wep-API-Get-All-Record.png 1344w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-11199" class="wp-caption-text">Wep API Get All Record</p></div></p>
<p>So far our READ operation is done. Now We will move into CREATE part.</p>
<h3><strong>Create Operation</strong></h3>
<p>First we will concentrate on the view part as of now. Just add the below codes to your view.</p>
<p>[html]<br />
&lt;div class=&#8221;form-group&#8221;&gt;<br />
&lt;label for=&#8221;email&#8221;&gt;Sbscribe here&lt;/label&gt;<br />
&lt;input type=&#8221;email&#8221; class=&#8221;form-control&#8221; id=&#8221;email&#8221; placeholder=&#8221;Enter email&#8221; [required=&#8221;string&#8221; ] data-ng-model=&#8221;mailid&#8221; /&gt;<br />
&lt;/div&gt;<br />
&lt;button type=&#8221;button&#8221; class=&#8221;btn btn-default&#8221; data-ng-click=&#8221;saveSubs();&#8221;&gt;Submit&lt;/button&gt;<br />
[/html]</p>
<p>This will give you an output as follows.</p>
<p><div id="attachment_11209" style="width: 441px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/02/View-Design-For-Create.png"><img decoding="async" aria-describedby="caption-attachment-11209" class="size-full wp-image-11209" src="http://sibeeshpassion.com/wp-content/uploads/2016/02/View-Design-For-Create.png" alt="View Design For Create" width="431" height="154" srcset="/wp-content/uploads/2016/02/View-Design-For-Create.png 431w, /wp-content/uploads/2016/02/View-Design-For-Create-300x107.png 300w, /wp-content/uploads/2016/02/View-Design-For-Create-400x143.png 400w" sizes="(max-width: 431px) 100vw, 431px" /></a><p id="caption-attachment-11209" class="wp-caption-text">View Design For Create</p></div></p>
<p>As you can see, we are firing the function <em>saveSubs()</em> in <em>data-ng-click</em>. So let us see what we need to write in it.</p>
<p>In the Controller.js you need to create a function as below.</p>
<p>[js]<br />
$scope.saveSubs = function () {<br />
var sub = {<br />
MailID: $scope.mailid,<br />
SubscribedDate: new Date()<br />
};<br />
var saveSubs = APIService.saveSubscriber(sub);<br />
saveSubs.then(function (d) {<br />
getAll();<br />
}, function (error) {<br />
console.log(&#8216;Oops! Something went wrong while saving the data.&#8217;)<br />
})<br />
};<br />
[/js]</p>
<p>Did you see that we are calling an another function which is in our APIService. So now we need to create a function <em>saveSubscriber</em> in Service.js. Shall we?</p>
<p>[js]<br />
this.saveSubscriber = function (sub) {<br />
return $http({<br />
method: &#8216;post&#8217;,<br />
data: sub,<br />
url: &#8216;api/Subscriber&#8217;<br />
});<br />
}<br />
[/js]</p>
<p>So all set, the rest is to create a function in our API Controller.</p>
<p>[csharp]<br />
// POST: api/Subscriber<br />
public void Post(tbl_Subscribers sub)<br />
{<br />
if (ModelState.IsValid)<br />
{<br />
myEntity.tbl_Subscribers.Add(sub);<br />
myEntity.SaveChanges();<br />
}<br />
}<br />
[/csharp]</p>
<p>That&#8217;s cool, now you will be able to create data through our API with the help of Angular JS. Now shall we move into UPDATE operation.</p>
<h3><strong>Update Operation</strong></h3>
<p>Before going to the code part we will do some changes in our table design. We are going to make one field (Mail ID field) editable when ever user double clicks in it. And of course we will update the edited data to the database when ever user leaves that field. Sounds cool? Now please change the view as follows.</p>
<p>[html]<br />
&lt;div id=&#8221;tblSubs&#8221; ng-controller=&#8221;APIController&#8221;&gt;<br />
&lt;table&gt;<br />
&lt;tr&gt;<br />
&lt;th&gt;ID&lt;/th&gt;<br />
&lt;th&gt;Email ID ( Double click to update)&lt;/th&gt;<br />
&lt;th&gt;Subscribed Date&lt;/th&gt;<br />
&lt;th&gt;&lt;/th&gt;<br />
&lt;/tr&gt;<br />
&lt;tbody data-ng-repeat=&#8221;sub in subscriber&#8221;&gt;<br />
&lt;tr&gt;<br />
&lt;td&gt;{{sub.SubscriberID}}&lt;/td&gt;<br />
&lt;td ng-blur=&#8221;updSubscriber(sub,$event)&#8221; ng-dblclick=&#8221;makeEditable($event)&#8221;&gt;{{sub.MailID}}&lt;/td&gt;<br />
&lt;td&gt;{{sub.SubscribedDate}}&lt;/td&gt;<br />
&lt;/tr&gt;<br />
&lt;/tbody&gt;<br />
&lt;/table&gt;<br />
&lt;div class=&#8221;form-group&#8221;&gt;<br />
&lt;label for=&#8221;email&#8221;&gt;Sbscribe here&lt;/label&gt;<br />
&lt;input type=&#8221;email&#8221; class=&#8221;form-control&#8221; id=&#8221;email&#8221; placeholder=&#8221;Enter email&#8221; [required=&#8221;string&#8221; ] data-ng-model=&#8221;mailid&#8221; /&gt;<br />
&lt;/div&gt;<br />
&lt;button type=&#8221;button&#8221; class=&#8221;btn btn-default&#8221; data-ng-click=&#8221;saveSubs();&#8221;&gt;Submit&lt;/button&gt;<br />
&lt;/div&gt;<br />
[/html]</p>
<p>The below is the main change we did.</p>
<p>[html]<br />
&lt;td ng-blur=&#8221;updSubscriber(sub,$event)&#8221; ng-dblclick=&#8221;makeEditable($event)&#8221;&gt;{{sub.MailID}}&lt;/td&gt;<br />
[/html]</p>
<p>In <em>ng-blur</em> we are calling the function <em>updSubscriber</em> with parameter $event and the current subscriber details. And in <em>ng-dblclick</em> we are calling the function <em>makeEditable</em> with parameter $event which actually holds the UI details and current events.</p>
<p>Below is the code for the function <em>makeEditable</em> in Controller.js</p>
<p>[js]<br />
$scope.makeEditable = function (obj) {<br />
obj.target.setAttribute(&#8220;contenteditable&#8221;, true);<br />
obj.target.focus();<br />
};<br />
[/js]</p>
<p>As you can see we are setting the attribute <em>contenteditable</em> to true using <em>setAttribute</em> function. Now we will look into the function <em>updSubscriber</em>.</p>
<p>Add a function in Controller.js</p>
<p>[js]<br />
$scope.updSubscriber = function (sub, eve) {<br />
sub.MailID = eve.currentTarget.innerText;<br />
var upd = APIService.updateSubscriber(sub);<br />
upd.then(function (d) {<br />
getAll();<br />
}, function (error) {<br />
console.log(&#8216;Oops! Something went wrong while updating the data.&#8217;)<br />
})<br />
};<br />
[/js]</p>
<p>Add a relative function in Service.js</p>
<p>[js]<br />
this.updateSubscriber = function (sub) {<br />
return $http({<br />
method: &#8216;put&#8217;,<br />
data: sub,<br />
url: &#8216;api/Subscriber&#8217;<br />
});<br />
}<br />
[/js]</p>
<p>Now we need to add a function in our Web API controller.</p>
<p>[csharp]<br />
// PUT: api/Subscriber/5<br />
public void Put(tbl_Subscribers sub)<br />
{<br />
if (ModelState.IsValid)<br />
{<br />
myEntity.Entry(sub).State = EntityState.Modified;<br />
try<br />
{<br />
myEntity.SaveChanges();<br />
}<br />
catch (Exception)<br />
{<br />
throw;<br />
}<br />
}<br />
}<br />
[/csharp]</p>
<p>Now you will be able to update your record. What is pending now? Yes, DELETE operation.</p>
<h3><strong>Delete Operation</strong></h3>
<p>Make some changes in the view as follows.</p>
<p>[html]<br />
&lt;tbody data-ng-repeat=&#8221;sub in subscriber&#8221;&gt;<br />
&lt;tr&gt;<br />
&lt;td&gt;{{sub.SubscriberID}}&lt;/td&gt;<br />
&lt;td ng-blur=&#8221;updSubscriber(sub,$event)&#8221; ng-dblclick=&#8221;makeEditable($event)&#8221;&gt;{{sub.MailID}}&lt;/td&gt;<br />
&lt;td&gt;{{sub.SubscribedDate}}&lt;/td&gt;<br />
&lt;td&gt;<br />
&lt;input type=&#8221;button&#8221; id=&#8221;Delete&#8221; value=&#8221;Delete&#8221; data-ng-click=&#8221;dltSubscriber(sub.SubscriberID)&#8221; /&gt;<br />
&lt;/td&gt;<br />
&lt;/tr&gt;<br />
&lt;/tbody&gt;<br />
[/html]</p>
<p>Now add the new function in Controller.js</p>
<p>[js]<br />
$scope.dltSubscriber = function (subID) {<br />
var dlt = APIService.deleteSubscriber(subID);<br />
dlt.then(function (d) {<br />
getAll();<br />
}, function (error) {<br />
console.log(&#8216;Oops! Something went wrong while deleting the data.&#8217;)<br />
})<br />
};<br />
[/js]</p>
<p>Create a service in Service.js now.</p>
<p>[js]<br />
this.deleteSubscriber = function (subID) {<br />
var url = &#8216;api/Subscriber/&#8217; + subID;<br />
return $http({<br />
method: &#8216;delete&#8217;,<br />
data: subID,<br />
url: url<br />
});<br />
}<br />
[/js]</p>
<p>Now it is time to create our delete method in Web API controller.</p>
<p>[csharp]<br />
// DELETE: api/Subscriber/5<br />
public void Delete(int id)<br />
{<br />
tbl_Subscribers dlt = myEntity.tbl_Subscribers.Find(id);<br />
if (dlt != null)<br />
{<br />
try<br />
{<br />
myEntity.tbl_Subscribers.Remove(dlt);<br />
myEntity.SaveChanges();<br />
}<br />
catch (Exception)<br />
{<br />
throw;<br />
}<br />
}<br />
}<br />
[/csharp]</p>
<p>That is all. We did it. Now build your application and see an output as follows.</p>
<p><div id="attachment_11211" style="width: 660px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/02/Web-API-With-Angular-JS1-e1454928109942.png"><img decoding="async" aria-describedby="caption-attachment-11211" class="size-full wp-image-11211" src="http://sibeeshpassion.com/wp-content/uploads/2016/02/Web-API-With-Angular-JS1-e1454928109942.png" alt="Web API With Angular JS" width="650" height="522" srcset="/wp-content/uploads/2016/02/Web-API-With-Angular-JS1-e1454928109942.png 650w, /wp-content/uploads/2016/02/Web-API-With-Angular-JS1-e1454928109942-300x241.png 300w, /wp-content/uploads/2016/02/Web-API-With-Angular-JS1-e1454928109942-400x321.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><p id="caption-attachment-11211" class="wp-caption-text">Web API With Angular JS</p></div></p>
<p>Have a happy coding.</p>
<h2><strong>Conclusion</strong></h2>
<p>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.</p>
<h2><strong>Your turn. What do you think?</strong></h2>
<p>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.</p>
<p>Kindest Regards<br />
Sibeesh Venu</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.sibeeshpassion.com/web-api-with-angular-js-3/feed/</wfw:commentRss>
			<slash:comments>14</slash:comments>
		
		
			</item>
	</channel>
</rss>
