<?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>MVC &#8211; Sibeesh Passion</title>
	<atom:link href="https://sibeeshpassion.com/tag/mvc/feed/" rel="self" type="application/rss+xml" />
	<link>https://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>MVC &#8211; Sibeesh Passion</title>
	<link>https://sibeeshpassion.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>LINQ Basic To Advanced &#8211; MVC Demo Application</title>
		<link>https://sibeeshpassion.com/linq-basic-to-advanced-mvc-demo-application/</link>
					<comments>https://sibeeshpassion.com/linq-basic-to-advanced-mvc-demo-application/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Mon, 15 May 2017 16:09:40 +0000</pubDate>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[CSharp]]></category>
		<category><![CDATA[LINQ]]></category>
		<category><![CDATA[LINQ Queries]]></category>
		<guid isPermaLink="false">http://sibeecst_passion.com/?p=12365</guid>

					<description><![CDATA[[toc] Introduction Here, in this post we are going to a see some LINQ queries, which covers both basics and advanced. LINQ queries are introduced few years back to offer a consistent way for working with data across many datasources and formats. In LINQ queries, you will always work with objects, which makes it simple to write. I hope you would have already written lots of LINQ queries already, if you haven&#8217;t, I strongly reccommend you to read this blog where you can find the answer for, why do we need to use LINQ?. Here I am going to create [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>[toc]</p>
<h3>Introduction</h3>
<p>Here, in this post we are going to a see some <a href="http://sibeeshpassion.com/tag/LINQ" target="_blank" rel="noopener noreferrer">LINQ</a> queries, which covers both basics and advanced. LINQ queries are introduced few years back to offer a consistent way for working with data across many datasources and formats. In LINQ queries, you will always work with objects, which makes it simple to write. I hope you would have already written lots of LINQ queries already, if you haven&#8217;t, I strongly reccommend you to read this <a href="https://docs.microsoft.com/en-us/dotnet/articles/csharp/programming-guide/concepts/linq/introduction-to-linq-queries" target="_blank" rel="noopener">blog </a> where you can find the answer for, why do we need to use LINQ?. Here I am going to create a <a href="http://sibeeshpassion.com/category/mvc/">MVC</a> demo application. I hope you will like this. Now let&#8217;s begin.</p>
<h3>Download Source Code</h3>
<li><a href="https://code.msdn.microsoft.com/LINQ-Basic-To-Advanced-MVC-cc3b8254" target="_blank" rel="noopener">LINQ_B_To_A</a></li>
<h3>Background</h3>
<p>Whenever I get a chance to write some server side codes in <a href="http://sibeeshpassion.com/category/csharp/" target="_blank" rel="noopener">C#</a>, I always write it using LINQ. And few weeks back, I was assigned to a training programme where my job was to teach LINQ, hence this post covers the the queries I have written for the training programme. Hope you will find it useful.</p>
<h3>Using the code</h3>
<p>A LINQ query can be written in two ways.</p>
<li>Query Syntax</li>
<li>Method Chain or Using dot(.) operator</li>
<p>There are so many articles available in the Internet on the topic LINQ, but most of them dont cover the differences of writing the queries in two possible ways, the motive of this article is to write the queries in both ways, so that you can understand the differnces.</p>
<p>As I mentioned, we are going to create an MVC application, we need to create it first and then configure the entity. Let&#8217;s go and do that.</p>
<h4>Create a database</h4>
<p>To get started with we need to configure our database first. To do so, either you can download the Wild World Importers from <a href="https://github.com/Microsoft/sql-server-samples/releases/tag/wide-world-importers-v1.0" target="_blank" rel="noopener">here</a> or you can run the script file included in the downlaod link above. </p>
<p>Once after you created the database, you can create your MVC application and Entity Data Model in it. </p>
<h4>Configuring MVC application with Entity Data Model</h4>
<p>By this time, I hope you would have configured your MVC application with Entity Data Model. Now it is time to create a controller and Entity object. </p>
<p>[csharp]<br />
using System;<br />
using System.Collections.Generic;<br />
using System.Data.Entity;<br />
using System.Linq;<br />
using System.Web;<br />
using System.Web.Mvc;<br />
using System.Windows.Forms;<br />
using LINQ_B_to_A.Models;<br />
namespace LINQ_B_to_A.Controllers<br />
{<br />
    public class HomeController : Controller<br />
    {<br />
        // GET: Home</p>
<p>        public MyDataModel DtContext { get; set; } = new MyDataModel();<br />
    }<br />
}<br />
[/csharp]</p>
<p>Now we can write some LINQ queries as everything is set to get started.</p>
<h4>Setting up the Index view with possible actions</h4>
<p>This is just to call the actions we are going write. Let&#8217;s see the Index page now. </p>
<p>[html]<br />
@{<br />
    ViewBag.Title = &quot;Index&quot;;<br />
    Layout = &quot;~/Views/Shared/_Layout.cshtml&quot;;<br />
}</p>
<p>&lt;h2&gt;Index&lt;/h2&gt;<br />
&lt;input type=&quot;button&quot; class=&quot;btn-info&quot; onclick=&quot;location.href=&#8217;@Url.Action(&quot;LoadAll&quot;,&quot;Home&quot;)&#8217;&quot; value=&quot;Load All &#8211; Query Expression&quot;/&gt;<br />
&lt;input type=&quot;button&quot; class=&quot;btn-info&quot; onclick=&quot;location.href=&#8217;@Url.Action(&quot;JoinWithWhere&quot;,&quot;Home&quot;)&#8217;&quot; value=&quot;Join With Where&quot; /&gt;<br />
&lt;input type=&quot;button&quot; class=&quot;btn-info&quot; onclick=&quot;location.href=&#8217;@Url.Action(&quot;LeftJoin&quot;,&quot;Home&quot;)&#8217;&quot; value=&quot;Left Join&quot; /&gt;<br />
&lt;input type=&quot;button&quot; class=&quot;btn-info&quot; onclick=&quot;location.href=&#8217;@Url.Action(&quot;DistinctSample&quot;,&quot;Home&quot;)&#8217;&quot; value=&quot;Distinct Sample&quot; /&gt;<br />
&lt;input type=&quot;button&quot; class=&quot;btn-info&quot; onclick=&quot;location.href=&#8217;@Url.Action(&quot;EqualsSamples&quot;,&quot;Home&quot;)&#8217;&quot; value=&quot;Equals Sample&quot; /&gt;<br />
&lt;input type=&quot;button&quot; class=&quot;btn-info&quot; onclick=&quot;location.href=&#8217;@Url.Action(&quot;NotEqualsSamples&quot;,&quot;Home&quot;)&#8217;&quot; value=&quot;Not Equals&quot; /&gt;<br />
&lt;input type=&quot;button&quot; class=&quot;btn-info&quot; onclick=&quot;location.href=&#8217;@Url.Action(&quot;PagingQueries&quot;,&quot;Home&quot;)&#8217;&quot; value=&quot;Paging Queries&quot; /&gt;<br />
&lt;input type=&quot;button&quot; class=&quot;btn-info&quot; onclick=&quot;location.href=&#8217;@Url.Action(&quot;MathQueries&quot;,&quot;Home&quot;)&#8217;&quot; value=&quot;Math Queries&quot; /&gt;<br />
&lt;input type=&quot;button&quot; class=&quot;btn-info&quot; onclick=&quot;location.href=&#8217;@Url.Action(&quot;StringQueries&quot;,&quot;Home&quot;)&#8217;&quot; value=&quot;String Queries&quot; /&gt;<br />
&lt;input type=&quot;button&quot; class=&quot;btn-info&quot; onclick=&quot;location.href=&#8217;@Url.Action(&quot;SelectMany&quot;,&quot;Home&quot;)&#8217;&quot; value=&quot;Select Many&quot; /&gt;<br />
[/html]</p>
<div id="attachment_12367" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-Index-View-e1494741059608.png"><img fetchpriority="high" decoding="async" aria-describedby="caption-attachment-12367" src="http://sibeeshpassion.com/wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-Index-View-e1494741059608.png" alt="LINQ Basic to Advanced Index View" width="634" height="197" class="size-full wp-image-12367" srcset="/wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-Index-View-e1494741059608.png 634w, /wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-Index-View-e1494741059608-300x93.png 300w, /wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-Index-View-e1494741059608-400x124.png 400w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-12367" class="wp-caption-text">LINQ Basic to Advanced Index View</p></div>
<h4>Normal Select Query With StartWith and Take</h4>
<p>Let&#8217;s have a look at the preceding query.</p>
<p>[csharp]<br />
/// &lt;summary&gt;<br />
        /// Linq query with Select<br />
        /// &lt;/summary&gt;<br />
        /// &lt;returns&gt;&lt;/returns&gt;<br />
        public ActionResult LoadAll()<br />
        {<br />
            var loadAllData = (from d in DtContext.Cities where d.CityName.StartsWith(&quot;C&quot;) select d).Take(10);</p>
<p>            //Method Chain Format<br />
            var loadAllData1 = DtContext.Cities.Where(d =&gt; d.CityName.StartsWith(&quot;C&quot;)).Take(10);</p>
<p>            return PartialView(loadAllData);<br />
        }<br />
[/csharp]</p>
<p>As you can see, we are just fetching the data from Cities in both ways. And we are using StartWith as a filter, which actually looks for the city names which starts with the letter C, and finally we are taking 10 elements from it. The first query is the &#8220;Query syntax&#8221; and the second one is &#8220;Method chain&#8221;. Personally I like the second way. How about you?</p>
<p>[html]<br />
@model IQueryable&lt;LINQ_B_to_A.Models.City&gt;<br />
&lt;style&gt;<br />
    dd, dt, pre {<br />
        border: 1px solid #ccc;<br />
        padding: 5px;<br />
        margin: 5px;<br />
        width: auto;<br />
        width: 20%;<br />
    }</p>
<p>    dd {<br />
        background-color: #a9a9a9<br />
    }<br />
    pre {<br />
        width: auto;<br />
    }<br />
&lt;/style&gt;<br />
&lt;dd&gt;City Names&lt;/dd&gt;<br />
@foreach (var ctyObj in Model)<br />
{<br />
    &lt;dt&gt;@ctyObj.CityName&lt;/dt&gt;<br />
}<br />
&lt;pre&gt;<br />
        public ActionResult LoadAll()<br />
        {<br />
            var loadAllData = (from d in DtContext.Cities where d.CityName.StartsWith(&quot;C&quot;) select d).Take(10);</p>
<p>            //Method Chain Format<br />
            var loadAllData1 = DtContext.Cities.Where(d =&gt; d.CityName.StartsWith(&quot;C&quot;)).Take(10);</p>
<p>            return PartialView(loadAllData);<br />
        }<br />
&lt;/pre&gt;<br />
[/html]</p>
<p>We are ready to see our first query in action now. </p>
<p>Let&#8217;s creat a partial view now to show the data we fetched. <a href="http://sibeeshpassion.com/wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-Normal-Select-Query-With-StartsWith-and-Take-e1494741383811.png"><img decoding="async" src="http://sibeeshpassion.com/wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-Normal-Select-Query-With-StartsWith-and-Take-e1494741383811.png" alt="LINQ Basic to Advanced Normal Select Query With StartsWith and Take" width="634" height="400" class="alignnone size-full wp-image-12368" srcset="/wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-Normal-Select-Query-With-StartsWith-and-Take-e1494741383811.png 634w, /wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-Normal-Select-Query-With-StartsWith-and-Take-e1494741383811-300x189.png 300w, /wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-Normal-Select-Query-With-StartsWith-and-Take-e1494741383811-400x252.png 400w" sizes="(max-width: 634px) 100vw, 634px" /></a></p>
<h4>JOIN Query</h4>
<p>To write a join, the query would be as preceding.</p>
<p>[csharp]<br />
/// &lt;summary&gt;<br />
        /// Linq query with join and where<br />
        /// &lt;/summary&gt;<br />
        /// &lt;returns&gt;&lt;/returns&gt;<br />
        public ActionResult JoinWithWhere()<br />
        {<br />
            var loadAllData = (from oOrders in DtContext.Orders<br />
                               join oOrderLines in DtContext.OrderLines<br />
                               on oOrders.OrderID equals oOrderLines.OrderID<br />
                               orderby oOrders.OrderID<br />
                               select new OrderAndOrderLines()<br />
                               {<br />
                                   OrderId = oOrders.OrderID,<br />
                                   Description = oOrderLines.Description,<br />
                                   Quantity = oOrderLines.Quantity<br />
                               }).Take(10);<br />
            //Method Chain Format<br />
            var asMethodChain = DtContext.Orders.Join(DtContext.OrderLines, oOrders =&gt; oOrders.OrderID,<br />
                    oOrderLines =&gt; oOrderLines.OrderID,<br />
                    (oOrders, oOrderLines) =&gt; new { oOrders, oOrderLines })<br />
                .OrderBy(@o =&gt; @o.oOrders.OrderID)<br />
                .Select(@s =&gt; new OrderAndOrderLines()<br />
                {<br />
                    OrderId = @s.oOrders.OrderID,<br />
                    Description = @s.oOrderLines.Description,<br />
                    Quantity = @s.oOrderLines.Quantity<br />
                }).Take(10);</p>
<p>            return PartialView(loadAllData);<br />
        }<br />
[/csharp]</p>
<p>In the above query we are just joining the tables Order and OrderLines with OrderID and to select we are using an another custom model OrderAndOrderLines. </p>
<p>[csharp]<br />
namespace LINQ_B_to_A.Models<br />
{<br />
    public partial class OrderAndOrderLines<br />
    {<br />
        public int OrderId { get; set; }<br />
        public string Description { get; set; }<br />
        public int? Quantity { get; set; }<br />
    }<br />
}<br />
[/csharp]</p>
<p>The view can be written as follows.</p>
<p>[html]<br />
@model IEnumerable&lt;LINQ_B_to_A.Models.OrderAndOrderLines&gt;<br />
&lt;style&gt;<br />
    td, th, thead,pre {<br />
        border: 1px solid #ccc;<br />
        padding: 5px;<br />
        margin: 5px;<br />
        width: auto;<br />
        width: 20%;<br />
    }</p>
<p>    caption {<br />
        background-color: #a9a9a9<br />
    }<br />
    pre {<br />
        width: auto;<br />
    }<br />
&lt;/style&gt;</p>
<p>&lt;table&gt;<br />
    &lt;caption&gt;Order Details&lt;/caption&gt;<br />
    &lt;tr&gt;<br />
        &lt;th&gt;Order ID&lt;/th&gt;<br />
        &lt;th&gt;Description&lt;/th&gt;<br />
        &lt;th&gt;Quantity&lt;/th&gt;<br />
    &lt;/tr&gt;<br />
    @foreach (var @item in Model)<br />
    {<br />
        &lt;tr&gt;<br />
            &lt;td&gt;@item.OrderId&lt;/td&gt;<br />
            &lt;td&gt;@item.Description&lt;/td&gt;<br />
            &lt;td&gt;@item.Quantity&lt;/td&gt;<br />
        &lt;/tr&gt;<br />
    }<br />
&lt;/table&gt;<br />
&lt;pre&gt;<br />
     public ActionResult JoinWithWhere()<br />
        {<br />
            var loadAllData = (from oOrders in DtContext.Orders<br />
                               join oOrderLines in DtContext.OrderLines<br />
                               on oOrders.OrderID equals oOrderLines.OrderID<br />
                               orderby oOrders.OrderID<br />
                               select new OrderAndOrderLines()<br />
                               {<br />
                                   OrderId = oOrders.OrderID,<br />
                                   Description = oOrderLines.Description,<br />
                                   Quantity = oOrderLines.Quantity<br />
                               }).Take(10);<br />
            //Method Chain Format<br />
            var asMethodChain = DtContext.Orders.Join(DtContext.OrderLines, oOrders =&gt; oOrders.OrderID,<br />
                    oOrderLines =&gt; oOrderLines.OrderID,<br />
                    (oOrders, oOrderLines) =&gt; new { oOrders, oOrderLines })<br />
                .OrderBy(o =&gt; o.oOrders.OrderID)<br />
                .Select(s =&gt; new OrderAndOrderLines()<br />
                {<br />
                    OrderId = s.oOrders.OrderID,<br />
                    Description = s.oOrderLines.Description,<br />
                    Quantity = s.oOrderLines.Quantity<br />
                }).Take(10);</p>
<p>            return PartialView(loadAllData);<br />
        }<br />
&lt;/pre&gt;<br />
[/html]</p>
<p>Once you run the action you can see the result as follows. </p>
<div id="attachment_12369" style="width: 1654px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-Join-With-Where-e1494742473978.png"><img decoding="async" aria-describedby="caption-attachment-12369" src="http://sibeeshpassion.com/wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-Join-With-Where-e1494742473978.png" alt="LINQ Basic to Advanced Join With Where" width="1644" height="821" class="size-full wp-image-12369" srcset="/wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-Join-With-Where-e1494742473978.png 634w, /wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-Join-With-Where-e1494742473978-300x150.png 300w, /wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-Join-With-Where-e1494742473978-400x200.png 400w" sizes="(max-width: 1644px) 100vw, 1644px" /></a><p id="caption-attachment-12369" class="wp-caption-text">LINQ Basic to Advanced Join With Where</p></div>
<h4>Left JOIN Query</h4>
<p>To write a Left join, the query would be as preceding.</p>
<p>[csharp]<br />
/// &lt;summary&gt;<br />
        /// Linq query with Left Join<br />
        /// &lt;/summary&gt;<br />
        /// &lt;returns&gt;&lt;/returns&gt;<br />
        public ActionResult LeftJoin()<br />
        {<br />
            var loadAllData = (from oOrder in DtContext.Orders<br />
                               join oOrderLine in DtContext.OrderLines<br />
                               on oOrder.OrderID equals oOrderLine.OrderID<br />
                               into lftOrder<br />
                               from afterJoined in lftOrder.DefaultIfEmpty()<br />
                               orderby oOrder.OrderID descending<br />
                               select new OrderAndOrderLines()<br />
                               {<br />
                                   OrderId = oOrder.OrderID,<br />
                                   Description = afterJoined.Description<br />
                               }).Take(10).ToList();<br />
            //Method Chain Format<br />
            var lftJoinMethodChain = (DtContext.Orders.GroupJoin(DtContext.OrderLines,<br />
                    oOrder =&gt; oOrder.OrderID, oOrderLine =&gt; oOrderLine.OrderID,<br />
                    (oOrder, lftJoin) =&gt; new { oOrder, lftJoin })<br />
                .SelectMany(@sm =&gt; @sm.lftJoin.DefaultIfEmpty(), (@sm, afterJoin) =&gt; new { @sm, afterJoin })<br />
                .OrderByDescending(@o =&gt; @o.sm.oOrder.OrderID)<br />
                .Select(@s =&gt; new OrderAndOrderLines()<br />
                {<br />
                    OrderId = @s.sm.oOrder.OrderID,<br />
                    Description = @s.afterJoin.Description<br />
                })).Take(10).ToList();</p>
<p>            return PartialView(loadAllData);<br />
        }<br />
[/csharp]</p>
<p>In the above query we are just joining the tables Order and OrderLines with OrderID and to select we are using an another custom model OrderAndOrderLines as our previous query. The differences you could find here are, using an &#8216;into&#8217; and &#8216;DefaultIfEmpty&#8217; statements. The DefaultIfEmpty is making sure that it returns empty if there is no appropriate rows found in the second table. </p>
<p>The view can be written as follows.</p>
<p>[html]<br />
@model IEnumerable&lt;LINQ_B_to_A.Models.OrderAndOrderLines&gt;<br />
&lt;style&gt;<br />
    td, th, thead, pre {<br />
        border: 1px solid #ccc;<br />
        padding: 5px;<br />
        margin: 5px;<br />
        width: auto;<br />
        width: 20%;<br />
    }</p>
<p>    caption {<br />
        background-color: #a9a9a9<br />
    }<br />
    pre {<br />
        width: auto;<br />
    }<br />
&lt;/style&gt;</p>
<p>&lt;table&gt;<br />
    &lt;caption&gt;Order Details&lt;/caption&gt;<br />
    &lt;tr&gt;<br />
        &lt;th&gt;Order ID&lt;/th&gt;<br />
        &lt;th&gt;Description&lt;/th&gt;<br />
        &lt;th&gt;Quantity&lt;/th&gt;<br />
    &lt;/tr&gt;<br />
    @foreach (var @item in Model)<br />
    {<br />
        &lt;tr&gt;<br />
            &lt;td&gt;@item.OrderId&lt;/td&gt;<br />
            &lt;td&gt;@item.Description&lt;/td&gt;<br />
            &lt;td&gt;@item.Quantity&lt;/td&gt;<br />
        &lt;/tr&gt;<br />
    }<br />
&lt;/table&gt;<br />
&lt;pre&gt;<br />
    public ActionResult LeftJoin()<br />
        {<br />
            var loadAllData = (from oOrder in DtContext.Orders<br />
                               join oOrderLine in DtContext.OrderLines<br />
                               on oOrder.OrderID equals oOrderLine.OrderID<br />
                               into lftOrder<br />
                               from afterJoined in lftOrder.DefaultIfEmpty()<br />
                               orderby oOrder.OrderID descending<br />
                               select new OrderAndOrderLines()<br />
                               {<br />
                                   OrderId = oOrder.OrderID,<br />
                                   Description = afterJoined.Description<br />
                               }).Take(10).ToList();<br />
            //Method Chain Format<br />
            var lftJoinMethodChain = (DtContext.Orders.GroupJoin(DtContext.OrderLines,<br />
                    oOrder =&gt; oOrder.OrderID, oOrderLine =&gt; oOrderLine.OrderID,<br />
                    (oOrder, lftJoin) =&gt; new { oOrder, lftJoin })<br />
                .SelectMany(sm =&gt; sm.lftJoin.DefaultIfEmpty(), (sm, afterJoin) =&gt; new { sm, afterJoin })<br />
                .OrderByDescending(o =&gt; o.sm.oOrder.OrderID)<br />
                .Select(s =&gt; new OrderAndOrderLines()<br />
                {<br />
                    OrderId = s.sm.oOrder.OrderID,<br />
                    Description = s.afterJoin.Description<br />
                })).Take(10).ToList();</p>
<p>            return PartialView(loadAllData);<br />
        }<br />
&lt;/pre&gt;<br />
[/html]</p>
<p>Once you run the action you can see the result as follows. </p>
<div id="attachment_12370" style="width: 1658px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-Left-Join-e1494742942417.png"><img decoding="async" aria-describedby="caption-attachment-12370" src="http://sibeeshpassion.com/wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-Left-Join-e1494742942417.png" alt="LINQ Basic to Advanced Left Join" width="1648" height="820" class="size-full wp-image-12370" srcset="/wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-Left-Join-e1494742942417.png 634w, /wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-Left-Join-e1494742942417-300x149.png 300w, /wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-Left-Join-e1494742942417-400x199.png 400w" sizes="(max-width: 1648px) 100vw, 1648px" /></a><p id="caption-attachment-12370" class="wp-caption-text">LINQ Basic to Advanced Left Join</p></div>
<p>As you can see in the image, the order id 200000 doesn&#8217;t has any appropriate rows in the second table, so it shows as empty.</p>
<h4>Distinct Query</h4>
<p>The below query shows how we can write simple distinct query.</p>
<p>[csharp]<br />
/// &lt;summary&gt;<br />
        /// Linq query Distinct sample<br />
        /// &lt;/summary&gt;<br />
        /// &lt;returns&gt;&lt;/returns&gt;<br />
        public ActionResult DistinctSample()<br />
        {<br />
            var distictSample = (from oOrder in DtContext.OrderLines<br />
                                 select oOrder.Description).Distinct().Take(10).ToList();</p>
<p>            //Method Chain Format<br />
            var distictAsMethodChain = (DtContext.OrderLines.Select(oOrder =&gt; oOrder.Description)).Distinct().Take(10).ToList();</p>
<p>            return PartialView(distictSample);<br />
        }<br />
[/csharp]</p>
<p>In the above query we use Distinct to make sure that only distict items are selected from the result. The view can be written as follows.</p>
<p>[html]<br />
@model  List&lt;string&gt;<br />
&lt;style&gt;<br />
    dd, dt, pre {<br />
        border: 1px solid #ccc;<br />
        padding: 5px;<br />
        margin: 5px;<br />
        width: auto;<br />
        width: 20%;<br />
    }</p>
<p>    dd {<br />
        background-color: #a9a9a9<br />
    }</p>
<p>    pre {<br />
        width: auto;<br />
    }<br />
&lt;/style&gt;<br />
&lt;dd&gt;Order Descriptions&lt;/dd&gt;<br />
@foreach (var orderLinesyObj in Model)<br />
{<br />
    &lt;dt&gt;@orderLinesyObj&lt;/dt&gt;<br />
}<br />
&lt;pre&gt;<br />
    public ActionResult DistinctSample()<br />
        {<br />
            var distictSample = (from oOrder in DtContext.OrderLines<br />
                                 select oOrder.Description).Distinct().Take(10).ToList();</p>
<p>            //Method Chain Format<br />
            var distictAsMethodChain = (DtContext.OrderLines.Select(oOrder =&gt; oOrder.Description)).Distinct().Take(10).ToList();</p>
<p>            return PartialView(distictSample);<br />
        }<br />
&lt;/pre&gt;<br />
[/html]</p>
<p>Once you run the action you can see the result as follows.</p>
<div id="attachment_12371" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-Distinct-Query-e1494743542508.png"><img decoding="async" aria-describedby="caption-attachment-12371" src="http://sibeeshpassion.com/wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-Distinct-Query-e1494743542508.png" alt="LINQ Basic to Advanced Distinct Query" width="634" height="372" class="size-full wp-image-12371" srcset="/wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-Distinct-Query-e1494743542508.png 634w, /wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-Distinct-Query-e1494743542508-300x176.png 300w, /wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-Distinct-Query-e1494743542508-400x235.png 400w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-12371" class="wp-caption-text">LINQ Basic to Advanced Distinct Query</p></div>
<h4>Equals and Not Equals Queries</h4>
<p>We can write the equals and not equals query as preceding.</p>
<p>[csharp]<br />
/// &lt;summary&gt;<br />
        /// Linq query Equals sample<br />
        /// &lt;/summary&gt;<br />
        /// &lt;returns&gt;&lt;/returns&gt;<br />
        public ActionResult EqualsSamples()<br />
        {<br />
            var objEquals = (from objCity in DtContext.Cities<br />
                             where objCity.CityName.Equals(&quot;Troy&quot;)<br />
                             select objCity).Take(2);<br />
            //Method Chain Format<br />
            var objEquals1 = DtContext.Cities.Where(d =&gt; d.CityName.Equals(&quot;Troy&quot;)).Take(2);</p>
<p>            return PartialView(&quot;OperatorSamples&quot;, objEquals);<br />
        }</p>
<p>        /// &lt;summary&gt;<br />
        /// Linq query Not Equals sample<br />
        /// &lt;/summary&gt;<br />
        /// &lt;returns&gt;&lt;/returns&gt;<br />
        public ActionResult NotEqualsSamples()<br />
        {<br />
            var objNotEquals = (from objCity in DtContext.Cities<br />
                                where objCity.CityName != &quot;Troy&quot;<br />
                                select objCity).Take(5);</p>
<p>            var objNotEquals1 = (from objCity in DtContext.Cities<br />
                                 where !objCity.CityName.Equals(&quot;Troy&quot;)<br />
                                 select objCity).Take(5);</p>
<p>            //Method Chain Format<br />
            var objNotEquals2 = DtContext.Cities.Where(d =&gt; d.CityName != &quot;Troy&quot;).Take(2);</p>
<p>            var objNotEquals3 = DtContext.Cities.Where(d =&gt; !d.CityName.Equals(&quot;Troy&quot;)).Take(2);</p>
<p>            return PartialView(&quot;OperatorSamples&quot;, objNotEquals);<br />
        }<br />
[/csharp]</p>
<p>The view can be written as follows.</p>
<p>[html]<br />
@model IQueryable&lt;LINQ_B_to_A.Models.City&gt;<br />
&lt;style&gt;<br />
    td, th, thead, pre {<br />
        border: 1px solid #ccc;<br />
        padding: 5px;<br />
        margin: 5px;<br />
        width: auto;<br />
        width: 20%;<br />
    }</p>
<p>    caption {<br />
        background-color: #a9a9a9<br />
    }</p>
<p>    pre {<br />
        width: auto;<br />
    }<br />
&lt;/style&gt;</p>
<p>    &lt;table&gt;<br />
        &lt;caption&gt;City Details&lt;/caption&gt;<br />
        &lt;tr&gt;<br />
            &lt;th&gt;City ID&lt;/th&gt;<br />
            &lt;th&gt;City Name&lt;/th&gt;<br />
            &lt;th&gt;City Location&lt;/th&gt;<br />
        &lt;/tr&gt;<br />
@foreach (var @item in Model)<br />
{<br />
    &lt;tr&gt;<br />
    &lt;td&gt;@item.CityID&lt;/td&gt;<br />
    &lt;td&gt;@item.CityName&lt;/td&gt;<br />
    &lt;td&gt;@item.Location&lt;/td&gt;<br />
    &lt;/tr&gt;<br />
}<br />
    &lt;/table&gt;<br />
&lt;caption&gt;Equals Oerator&lt;/caption&gt;<br />
&lt;pre&gt;<br />
    public ActionResult EqualsSamples()<br />
        {<br />
            var objEquals = (from objCity in DtContext.Cities<br />
                                       where objCity.CityName.Equals(&quot;Troy&quot;)<br />
                                       select objCity).Take(2);<br />
            //Method Chain Format<br />
            var objEquals1 = DtContext.Cities.Where(d =&gt; d.CityName.Equals(&quot;Troy&quot;)).Take(2);</p>
<p>            return PartialView(&quot;OperatorSamples&quot;, objEquals);<br />
        }</p>
<p>        public ActionResult NotEqualsSamples()<br />
        {<br />
            var objNotEquals = (from objCity in DtContext.Cities<br />
                where objCity.CityName != &quot;Troy&quot;<br />
                select objCity).Take(5);</p>
<p>            var objNotEquals1 = (from objCity in DtContext.Cities<br />
                where !objCity.CityName.Equals(&quot;Troy&quot;)<br />
                select objCity).Take(5);</p>
<p>            //Method Chain Format<br />
            var objNotEquals2 = DtContext.Cities.Where(d =&gt; d.CityName != &quot;Troy&quot;).Take(2);</p>
<p>            var objNotEquals3 = DtContext.Cities.Where(d =&gt; !d.CityName.Equals(&quot;Troy&quot;)).Take(2);</p>
<p>            return PartialView(&quot;OperatorSamples&quot;, objNotEquals);<br />
        }</p>
<p>        public ActionResult PagingQueries()<br />
        {<br />
            var objNotEquals = (from objCity in DtContext.Cities<br />
                where objCity.CityName != &quot;Troy&quot;<br />
                orderby objCity.CityName ascending<br />
                select objCity).Skip(5).Take(5);</p>
<p>            //Method Chain Format<br />
            var objNotEquals2 = DtContext.Cities.Where(d =&gt; d.CityName != &quot;Troy&quot;).Skip(5).Take(5);</p>
<p>            return PartialView(&quot;OperatorSamples&quot;, objNotEquals);<br />
        }<br />
&lt;/pre&gt;<br />
[/html]</p>
<p>Once you run the action you can see the result as follows.</p>
<div id="attachment_12372" style="width: 1622px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-Equals-and-Not-Equals-e1494744042305.png"><img decoding="async" aria-describedby="caption-attachment-12372" src="http://sibeeshpassion.com/wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-Equals-and-Not-Equals-e1494744042305.png" alt="LINQ Basic to Advanced Equals and Not Equals" width="1612" height="560" class="size-full wp-image-12372" srcset="/wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-Equals-and-Not-Equals-e1494744042305.png 634w, /wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-Equals-and-Not-Equals-e1494744042305-300x104.png 300w, /wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-Equals-and-Not-Equals-e1494744042305-400x139.png 400w" sizes="(max-width: 1612px) 100vw, 1612px" /></a><p id="caption-attachment-12372" class="wp-caption-text">LINQ Basic to Advanced Equals and Not Equals</p></div>
<h4>LINQ Paging Queries</h4>
<p>Paging queries are always important as we work in some grid controls, with LINQ those are very easy. Let&#8217;s see one of that query. </p>
<p>[csharp]<br />
/// &lt;summary&gt;<br />
        /// Linq Paging Queries<br />
        /// &lt;/summary&gt;<br />
        /// &lt;returns&gt;&lt;/returns&gt;<br />
        public ActionResult PagingQueries()<br />
        {<br />
            var objNotEquals = (from objCity in DtContext.Cities<br />
                                where objCity.CityName != &quot;Troy&quot;<br />
                                orderby objCity.CityName ascending<br />
                                select objCity).Skip(5).Take(5);</p>
<p>            //Method Chain Format<br />
            var objNotEquals2 = DtContext.Cities.Where(d =&gt; d.CityName != &quot;Troy&quot;).Skip(5).Take(5);</p>
<p>            return PartialView(&quot;OperatorSamples&quot;, objNotEquals);<br />
        }<br />
[/csharp]</p>
<p>Once you run the action you can see the result as follows.</p>
<div id="attachment_12373" style="width: 1611px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-Paging-Queries-e1494744396637.png"><img decoding="async" aria-describedby="caption-attachment-12373" src="http://sibeeshpassion.com/wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-Paging-Queries-e1494744396637.png" alt="LINQ Basic to Advanced Paging Queries" width="1601" height="862" class="size-full wp-image-12373" srcset="/wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-Paging-Queries-e1494744396637.png 634w, /wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-Paging-Queries-e1494744396637-300x161.png 300w, /wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-Paging-Queries-e1494744396637-400x215.png 400w" sizes="(max-width: 1601px) 100vw, 1601px" /></a><p id="caption-attachment-12373" class="wp-caption-text">LINQ Basic to Advanced Paging Queries</p></div>
<h4>LINQ Math Queries</h4>
<p>Here we are going to write the possible Math functions in our LINQ query.</p>
<p>[csharp]<br />
/// &lt;summary&gt;<br />
        /// Math Queries<br />
        /// &lt;/summary&gt;<br />
        /// &lt;returns&gt;&lt;/returns&gt;<br />
        public ActionResult MathQueries()<br />
        {<br />
            var objMath = (from objInv in DtContext.InvoiceLines<br />
                           where objInv.ExtendedPrice &gt; 10 &amp;&amp; objInv.Quantity &lt; 15<br />
                           orderby objInv.InvoiceLineID descending<br />
                           select new MathClass()<br />
                           {<br />
                               Actual = objInv.ExtendedPrice,<br />
                               Round = Math.Round(objInv.ExtendedPrice),<br />
                               Floor = Math.Floor(objInv.ExtendedPrice),<br />
                               Ceiling = Math.Ceiling(objInv.ExtendedPrice),<br />
                               Abs = Math.Abs(objInv.ExtendedPrice)<br />
                           }).Take(10);</p>
<p>            //Method Chain Format<br />
            var objMath2 = DtContext.InvoiceLines<br />
                .Where(objInv =&gt; objInv.ExtendedPrice &gt; 10 &amp;&amp; objInv.Quantity &lt; 15)<br />
                .OrderByDescending(o =&gt; o.InvoiceLineID)<br />
                .Select(objInv =&gt; new MathClass()<br />
                {<br />
                    Actual = objInv.ExtendedPrice,<br />
                    Round = Math.Round(objInv.ExtendedPrice),<br />
                    Floor = Math.Floor(objInv.ExtendedPrice),<br />
                    Ceiling = Math.Ceiling(objInv.ExtendedPrice),<br />
                    Abs = Math.Abs(objInv.ExtendedPrice)<br />
                }).Take(10);</p>
<p>            return PartialView(&quot;MathQueries&quot;, objMath);<br />
        }<br />
[/csharp]</p>
<p>As you can see we have written most of the possible Math functions in our query and selecting with a custome model MathClass.</p>
<p>[csharp]<br />
namespace LINQ_B_to_A.Models<br />
{<br />
    public partial class MathClass<br />
    {<br />
        public decimal Actual { get; set; }<br />
        public decimal Round { get; set; }<br />
        public decimal Floor { get; set; }<br />
        public decimal Ceiling { get; set; }<br />
        public decimal Abs { get; set; }<br />
    }<br />
}<br />
[/csharp]</p>
<p>Let&#8217;s see the view now. </p>
<p>[html]</p>
<p>@model IQueryable&lt;LINQ_B_to_A.Models.MathClass&gt;<br />
&lt;style&gt;<br />
    td, th, thead, pre {<br />
        border: 1px solid #ccc;<br />
        padding: 5px;<br />
        margin: 5px;<br />
        width: auto;<br />
        width: 20%;<br />
    }</p>
<p>    caption {<br />
        background-color: #a9a9a9<br />
    }</p>
<p>    pre {<br />
        width: auto;<br />
    }<br />
&lt;/style&gt;</p>
<p>&lt;table&gt;<br />
    &lt;caption&gt;Math Operators&lt;/caption&gt;<br />
    &lt;tr&gt;</p>
<p>    &lt;/tr&gt;<br />
    @foreach (var @item in Model)<br />
    {<br />
        &lt;tr&gt;<br />
            &lt;td&gt;Actual: @item.Actual&lt;/td&gt;<br />
            &lt;td&gt;Round: @item.Round&lt;/td&gt;<br />
            &lt;td&gt;Floor: @item.Floor&lt;/td&gt;<br />
            &lt;td&gt;Ceiling: @item.Ceiling&lt;/td&gt;<br />
            &lt;td&gt;Abs: @item.Abs&lt;/td&gt;<br />
        &lt;/tr&gt;<br />
    }<br />
&lt;/table&gt;<br />
&lt;pre&gt;<br />
    public ActionResult MathQueries()<br />
        {<br />
            var objMath = (from objInv in DtContext.InvoiceLines<br />
                          where objInv.ExtendedPrice &gt; 10 &amp;&amp; objInv.Quantity &lt; 15<br />
                          orderby objInv.InvoiceLineID descending<br />
                          select new MathClass()<br />
                          {<br />
                              Actual = objInv.ExtendedPrice,<br />
                              Round = Math.Round(objInv.ExtendedPrice),<br />
                              Floor = Math.Floor(objInv.ExtendedPrice),<br />
                              Ceiling = Math.Ceiling(objInv.ExtendedPrice),<br />
                              Abs = Math.Abs(objInv.ExtendedPrice)<br />
                          }).Take(10);</p>
<p>            //Method Chain Format<br />
            var objMath2 = DtContext.InvoiceLines<br />
                .Where(objInv =&gt; objInv.ExtendedPrice &gt; 10 &amp;&amp; objInv.Quantity &lt; 15)<br />
                .OrderByDescending(o =&gt; o.InvoiceLineID)<br />
                .Select(objInv =&gt; new MathClass()<br />
                {<br />
                    Actual = objInv.ExtendedPrice,<br />
                    Round = Math.Round(objInv.ExtendedPrice),<br />
                    Floor = Math.Floor(objInv.ExtendedPrice),<br />
                    Ceiling = Math.Ceiling(objInv.ExtendedPrice),<br />
                    Abs = Math.Abs(objInv.ExtendedPrice)<br />
                }).Take(10);</p>
<p>            return PartialView(&quot;MathQueries&quot;, objMath);<br />
        }<br />
&lt;/pre&gt;<br />
[/html]</p>
<p>See the result now.</p>
<div id="attachment_12374" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-Math-Queries-e1494744783496.png"><img decoding="async" aria-describedby="caption-attachment-12374" src="http://sibeeshpassion.com/wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-Math-Queries-e1494744783496.png" alt="LINQ Basic to Advanced Math Queries" width="634" height="673" class="size-full wp-image-12374" srcset="/wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-Math-Queries-e1494744783496.png 336w, /wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-Math-Queries-e1494744783496-283x300.png 283w, /wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-Math-Queries-e1494744783496-400x425.png 400w, /wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-Math-Queries-e1494744783496-565x600.png 565w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-12374" class="wp-caption-text">LINQ Basic to Advanced Math Queries</p></div>
<h4>LINQ String Queries</h4>
<p>As we saw the Math queries, here we are going to write the possible String functions in our LINQ query.</p>
<p>[csharp]<br />
/// &lt;summary&gt;<br />
        /// String Queries<br />
        /// &lt;/summary&gt;<br />
        /// &lt;returns&gt;&lt;/returns&gt;<br />
        public ActionResult StringQueries()<br />
        {<br />
            var objString = (from objInv in DtContext.InvoiceLines<br />
                             where objInv.ExtendedPrice &gt; 10 &amp;&amp; objInv.Quantity &lt; 15<br />
                             orderby objInv.InvoiceLineID descending<br />
                             select new StringClass()<br />
                             {<br />
                                 Actual = objInv.Description,<br />
                                 Insert = objInv.Description.Insert(2, &quot;sibeeshpassion&quot;),<br />
                                 Remove = objInv.Description.Remove(1, 1),<br />
                                 Substring = objInv.Description.Substring(2, 3),<br />
                                 ToLower = objInv.Description.ToLower(),<br />
                                 ToUpper = objInv.Description.ToUpper(),<br />
                                 TrimEnd = objInv.Description.TrimEnd(),<br />
                                 TrimStart = objInv.Description.TrimStart()<br />
                             }).Take(2);</p>
<p>            //Method Chain Format<br />
            var objString2 = DtContext.InvoiceLines<br />
                .Where(objInv =&gt; objInv.ExtendedPrice &gt; 10 &amp;&amp; objInv.Quantity &lt; 15)<br />
                .OrderByDescending(o =&gt; o.InvoiceLineID)<br />
                .Select(objInv =&gt; new StringClass()<br />
                {<br />
                    Actual = objInv.Description,<br />
                    Insert = objInv.Description.Insert(2, &quot;sibeeshpassion&quot;),<br />
                    Remove = objInv.Description.Remove(1, 1),<br />
                    Substring = objInv.Description.Substring(2, 3),<br />
                    ToLower = objInv.Description.ToLower(),<br />
                    ToUpper = objInv.Description.ToUpper(),<br />
                    TrimEnd = objInv.Description.TrimEnd(),<br />
                    TrimStart = objInv.Description.TrimStart()<br />
                }).Take(2);</p>
<p>            return PartialView(&quot;StringQueries&quot;, objString);<br />
        }<br />
[/csharp]</p>
<p>As you can see, here we are using a custom model StringClass.</p>
<p>[csharp]<br />
namespace LINQ_B_to_A.Models<br />
{<br />
    public partial class StringClass<br />
    {<br />
        public string Actual { get; set; }<br />
        public string Insert { get; set; }<br />
        public string Remove { get; set; }<br />
        public string Substring { get; set; }<br />
        public string ToUpper { get; set; }<br />
        public string ToLower { get; set; }<br />
        public string TrimStart { get; set; }<br />
        public string TrimEnd { get; set; }<br />
    }<br />
}<br />
[/csharp]</p>
<p>Let&#8217;s see the view now. </p>
<p>[html]</p>
<p>@model IQueryable&lt;LINQ_B_to_A.Models.StringClass&gt;<br />
&lt;style&gt;<br />
    td, th, thead, pre {<br />
        border: 1px solid #ccc;<br />
        padding: 5px;<br />
        margin: 5px;<br />
        width: auto;<br />
        width: 20%;<br />
    }</p>
<p>    caption {<br />
        background-color: #a9a9a9<br />
    }</p>
<p>    pre {<br />
        width: auto;<br />
    }<br />
&lt;/style&gt;</p>
<p>&lt;table&gt;<br />
    &lt;caption&gt;String Operators&lt;/caption&gt;<br />
    &lt;tr&gt;</p>
<p>    &lt;/tr&gt;<br />
    @foreach (var @item in Model)<br />
    {<br />
        &lt;tr&gt;<br />
            &lt;td&gt;Actual: @item.Actual&lt;/td&gt;<br />
            &lt;td&gt;Insert: @item.Insert&lt;/td&gt;<br />
            &lt;td&gt;Remove: @item.Remove&lt;/td&gt;<br />
            &lt;td&gt;Substring: @item.Substring&lt;/td&gt;<br />
            &lt;td&gt;ToLower: @item.ToLower&lt;/td&gt;<br />
            &lt;td&gt;ToUpper: @item.ToUpper&lt;/td&gt;<br />
            &lt;td&gt;TrimEnd: @item.TrimEnd&lt;/td&gt;<br />
            &lt;td&gt;TrimStart: @item.TrimStart&lt;/td&gt;<br />
        &lt;/tr&gt;<br />
    }<br />
&lt;/table&gt;<br />
&lt;pre&gt;<br />
        public ActionResult StringQueries()<br />
        {<br />
            var objString = (from objInv in DtContext.InvoiceLines<br />
                where objInv.ExtendedPrice &gt; 10 &amp;&amp; objInv.Quantity &lt; 15<br />
                orderby objInv.InvoiceLineID descending<br />
                select new StringClass()<br />
                {</p>
<p>                    Actual = objInv.Description,<br />
                    Insert = objInv.Description.Insert(2,&quot;sibeeshpassion&quot;),<br />
                    Remove = objInv.Description.Remove(1,1),<br />
                    Substring = objInv.Description.Substring(2,3),<br />
                    ToLower = objInv.Description.ToLower(),<br />
                    ToUpper = objInv.Description.ToUpper(),<br />
                    TrimEnd = objInv.Description.TrimEnd(),<br />
                    TrimStart = objInv.Description.TrimStart()<br />
                }).Take(2);</p>
<p>            //Method Chain Format<br />
            var objString2 = DtContext.InvoiceLines<br />
                .Where(objInv =&gt; objInv.ExtendedPrice &gt; 10 &amp;&amp; objInv.Quantity &lt; 15)<br />
                .OrderByDescending(o =&gt; o.InvoiceLineID)<br />
                .Select(objInv =&gt; new StringClass()<br />
                {<br />
                    Actual = objInv.Description,<br />
                    Insert = objInv.Description.Insert(2, &quot;sibeeshpassion&quot;),<br />
                    Remove = objInv.Description.Remove(1, 1),<br />
                    Substring = objInv.Description.Substring(2, 3),<br />
                    ToLower = objInv.Description.ToLower(),<br />
                    ToUpper = objInv.Description.ToUpper(),<br />
                    TrimEnd = objInv.Description.TrimEnd(),<br />
                    TrimStart = objInv.Description.TrimStart()<br />
                }).Take(2);</p>
<p>            return PartialView(&quot;StringQueries&quot;, objString);<br />
        }<br />
&lt;/pre&gt;<br />
[/html]</p>
<p>Now see the result.</p>
<div id="attachment_12375" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-String-Queries-e1494745369956.png"><img decoding="async" aria-describedby="caption-attachment-12375" src="http://sibeeshpassion.com/wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-String-Queries-e1494745369956.png" alt="LINQ Basic to Advanced String Queries" width="634" height="300" class="size-full wp-image-12375" srcset="/wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-String-Queries-e1494745369956.png 634w, /wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-String-Queries-e1494745369956-300x142.png 300w, /wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-String-Queries-e1494745369956-400x189.png 400w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-12375" class="wp-caption-text">LINQ Basic to Advanced String Queries</p></div>
<h4>SelectMany Query</h4>
<p>A SelectMany query flattern the result to a single dimentional collection, so to loop through the result we just need only one loop. </p>
<div id="attachment_12377" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-SelectMany-Tooltip-e1494746794913.png"><img decoding="async" aria-describedby="caption-attachment-12377" src="http://sibeeshpassion.com/wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-SelectMany-Tooltip-e1494746794913.png" alt="LINQ Basic to Advanced SelectMany Tooltip" width="634" height="104" class="size-full wp-image-12377" srcset="/wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-SelectMany-Tooltip-e1494746794913.png 634w, /wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-SelectMany-Tooltip-e1494746794913-300x49.png 300w, /wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-SelectMany-Tooltip-e1494746794913-400x66.png 400w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-12377" class="wp-caption-text">LINQ Basic to Advanced SelectMany Tooltip</p></div>
<p>If you use the normal Select, you will be getting a list of lists, thus you will have to use two loops to get the datas.</p>
<div id="attachment_12378" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-Select-Tooltip-e1494746906690.png"><img decoding="async" aria-describedby="caption-attachment-12378" src="http://sibeeshpassion.com/wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-Select-Tooltip-e1494746906690.png" alt="LINQ Basic to Advanced Select Tooltip" width="634" height="83" class="size-full wp-image-12378" srcset="/wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-Select-Tooltip-e1494746906690.png 634w, /wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-Select-Tooltip-e1494746906690-300x39.png 300w, /wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-Select-Tooltip-e1494746906690-400x52.png 400w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-12378" class="wp-caption-text">LINQ Basic to Advanced Select Tooltip</p></div>
<p>[csharp]<br />
 /// &lt;summary&gt;<br />
        /// Linq query with SelectMany<br />
        /// &lt;/summary&gt;<br />
        /// &lt;returns&gt;&lt;/returns&gt;<br />
        public ActionResult SelectMany()<br />
        {<br />
            var selectMany = DtContext.Orders.SelectMany(order =&gt; order.Invoices).Take(10);<br />
            var select = DtContext.Orders.Select(order =&gt; order.Invoices).Take(10);<br />
            return PartialView(&quot;SelectMany&quot;, selectMany);<br />
        }<br />
[/csharp]</p>
<p>Let&#8217;s see the view now. </p>
<p>[html]<br />
@model IQueryable&lt;LINQ_B_to_A.Models.Invoice&gt;<br />
&lt;style&gt;<br />
    td, th, thead, pre {<br />
        border: 1px solid #ccc;<br />
        padding: 5px;<br />
        margin: 5px;<br />
        width: auto;<br />
        width: 20%;<br />
    }</p>
<p>    caption {<br />
        background-color: #a9a9a9<br />
    }</p>
<p>    pre {<br />
        width: auto;<br />
    }<br />
&lt;/style&gt;</p>
<p>&lt;table&gt;<br />
    &lt;caption&gt;Invoice Details&lt;/caption&gt;<br />
    &lt;tr&gt;<br />
        &lt;th&gt;Order ID&lt;/th&gt;<br />
        &lt;th&gt;Invoice ID&lt;/th&gt;<br />
        &lt;th&gt;Invoice Date&lt;/th&gt;<br />
    &lt;/tr&gt;<br />
    @foreach (var @item in Model)<br />
    {<br />
        &lt;tr&gt;<br />
            &lt;td&gt;@item.OrderID&lt;/td&gt;<br />
            &lt;td&gt;@item.InvoiceID&lt;/td&gt;<br />
            &lt;td&gt;@item.InvoiceDate&lt;/td&gt;<br />
        &lt;/tr&gt;<br />
    }<br />
&lt;/table&gt;<br />
&lt;caption&gt;Select Many&lt;/caption&gt;<br />
&lt;pre&gt;<br />
     /// &lt;summary&gt;<br />
        /// Linq query with SelectMany<br />
        /// &lt;/summary&gt;<br />
        /// &lt;returns&gt;&lt;/returns&gt;<br />
        public ActionResult SelectMany()<br />
        {<br />
            var selectMany = DtContext.Orders.SelectMany(order =&gt; order.Invoices).Take(10);<br />
            var select = DtContext.Orders.Select(order =&gt; order.Invoices).Take(10);<br />
            return PartialView(&quot;SelectMany&quot;, selectMany);<br />
        }<br />
&lt;/pre&gt;<br />
[/html]</p>
<p>Now see the result.</p>
<p>That&#8217;s all for today, I will come with another set of LINQ queries in the next part. Till then, bye.</p>
<div id="attachment_12379" style="width: 952px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-SelectMany-e1494747140197.png"><img decoding="async" aria-describedby="caption-attachment-12379" src="http://sibeeshpassion.com/wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-SelectMany-e1494747140197.png" alt="LINQ Basic to Advanced SelectMany" width="942" height="597" class="size-full wp-image-12379" srcset="/wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-SelectMany-e1494747140197.png 634w, /wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-SelectMany-e1494747140197-300x190.png 300w, /wp-content/uploads/2017/05/LINQ-Basic-to-Advanced-SelectMany-e1494747140197-400x254.png 400w" sizes="(max-width: 942px) 100vw, 942px" /></a><p id="caption-attachment-12379" class="wp-caption-text">LINQ Basic to Advanced SelectMany</p></div>
<h3>Conclusion</h3>
<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>
<h3>Your turn. What do you think?</h3>
<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://sibeeshpassion.com/linq-basic-to-advanced-mvc-demo-application/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>MVC CRUD Actions Using Knockout JS</title>
		<link>https://sibeeshpassion.com/mvc-crud-actions-using-knockout-js/</link>
					<comments>https://sibeeshpassion.com/mvc-crud-actions-using-knockout-js/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Sun, 11 Dec 2016 16:13:27 +0000</pubDate>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Knockout JS]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[CRUD In Knockout JS]]></category>
		<category><![CDATA[MVC And Knockout JS]]></category>
		<category><![CDATA[MVC CRUD]]></category>
		<guid isPermaLink="false">http://sibeecst_passion.com/?p=11979</guid>

					<description><![CDATA[In this post we are going to create a MVC CRUD application with the help of Knockout JS. We will be using SQL database and Visual Studio for our development. If you are new to MVC, I strongly recommend you to read my previous post about MVC here. Now let&#8217;s begin. Download source code MVC CRUD Actions Using Knockout JS Introduction about Knockout JS According to Knockout JS documentation Knockout is a JavaScript library that helps you to create rich, responsive display and editor user interfaces with a clean underlying data model. Any time you have sections of UI that [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>In this post we are going to create a <a href="http://sibeeshpassion.com/category/MVC" target="_blank" rel="noopener">MVC</a> CRUD application with the help of <a href="http://sibeeshpassion.com/category/Knockout-JS" target="_blank" rel="noopener">Knockout JS</a>. We will be using <a href="http://sibeeshpassion.com/category/SQL" target="_blank" rel="noopener">SQL </a> database and <a href="http://sibeeshpassion.com/category/Visual-Studio/" target="_blank" rel="noopener">Visual Studio</a> for our development. If you are new to MVC, I strongly recommend you to read my previous post about MVC <a href="http://sibeeshpassion.com/category/MVC" target="_blank" rel="noopener">here</a>. Now let&#8217;s begin.</p>
<p><strong>Download source code</strong></p>
<li>
<a href="https://code.msdn.microsoft.com/MVC-CRUD-Actions-Using-fb523b40" target="_blank" rel="noopener">MVC CRUD Actions Using Knockout JS</a>
</li>
<p><strong>Introduction about Knockout JS</strong></p>
<p>According to <a href="http://knockoutjs.com/" target="_blank" rel="noopener">Knockout JS documentation</a> <strong>Knockout</strong> is a <a href="http://sibeeshpassion.com/category/JavaScript" target="_blank" rel="noopener">JavaScript</a> library that helps you to create rich, responsive display and editor user interfaces with a clean underlying data model. Any time you have sections of UI that update dynamically (e.g., changing depending on the user’s actions or when an external data source changes), KO can help you implement it more simply and maintainable.</p>
<p>It has benefits as,</p>
<p><em>Pure JavaScript library</em> &#8211; works with any server or client-side technology<br />
<em>Can be added on top of your existing web application</em> without requiring major architectural changes<br />
<em>Compact</em> &#8211; around 13kb after gzipping<br />
<em>Works on any mainstream browser</em> (IE 6+, Firefox 2+, Chrome, Safari, Edge, others)<br />
<em>Comprehensive suite of specifications</em> (developed BDD-style) means its correct functioning can easily be verified on new browsers and platforms.</p>
<p><strong>Background</strong></p>
<p>As I am working on a project which uses Knockout for binding the server data, a friend of mine requested me to create a CRUD application with Knockout, so that he can easily learn it. I just accepted his request and here we are going to create a MVC CRUD application with the help of Knockout JS. I hope you will like this. </p>
<p><strong>Create an Empty MVC application</strong></p>
<p>To get started we will create an empty MVC application as follows.</p>
<div id="attachment_11980" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/12/Add_new_empty_MVC_project-e1481467845633.png"><img decoding="async" aria-describedby="caption-attachment-11980" src="http://sibeeshpassion.com/wp-content/uploads/2016/12/Add_new_empty_MVC_project-e1481467845633.png" alt="add_new_empty_mvc_project" width="634" height="494" class="size-full wp-image-11980" srcset="/wp-content/uploads/2016/12/Add_new_empty_MVC_project-e1481467845633.png 458w, /wp-content/uploads/2016/12/Add_new_empty_MVC_project-e1481467845633-300x234.png 300w, /wp-content/uploads/2016/12/Add_new_empty_MVC_project-e1481467845633-400x312.png 400w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-11980" class="wp-caption-text">add_new_empty_mvc_project</p></div>
<p><strong>Creating database and Entity Data Model</strong></p>
<p>Here I am creating a database with name &#8220;TrialDB&#8221;, you can always create a DB by running the query given below. </p>
<p>[sql]<br />
USE [master]<br />
GO</p>
<p>/****** Object:  Database [TrialDB]    Script Date: 20-11-2016 03:54:53 PM ******/<br />
CREATE DATABASE [TrialDB]<br />
 CONTAINMENT = NONE<br />
 ON  PRIMARY<br />
( NAME = N&#8217;TrialDB&#8217;, FILENAME = N&#8217;C:\Program Files\Microsoft SQL Server\MSSQL13.SQLEXPRESS\MSSQL\DATA\TrialDB.mdf&#8217; , SIZE = 8192KB , MAXSIZE = UNLIMITED, FILEGROWTH = 65536KB )<br />
 LOG ON<br />
( NAME = N&#8217;TrialDB_log&#8217;, FILENAME = N&#8217;C:\Program Files\Microsoft SQL Server\MSSQL13.SQLEXPRESS\MSSQL\DATA\TrialDB_log.ldf&#8217; , SIZE = 8192KB , MAXSIZE = 2048GB , FILEGROWTH = 65536KB )<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET COMPATIBILITY_LEVEL = 130<br />
GO</p>
<p>IF (1 = FULLTEXTSERVICEPROPERTY(&#8216;IsFullTextInstalled&#8217;))<br />
begin<br />
EXEC [TrialDB].[dbo].[sp_fulltext_database] @action = &#8216;enable&#8217;<br />
end<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET ANSI_NULL_DEFAULT OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET ANSI_NULLS OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET ANSI_PADDING OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET ANSI_WARNINGS OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET ARITHABORT OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET AUTO_CLOSE OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET AUTO_SHRINK OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET AUTO_UPDATE_STATISTICS ON<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET CURSOR_CLOSE_ON_COMMIT OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET CURSOR_DEFAULT  GLOBAL<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET CONCAT_NULL_YIELDS_NULL OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET NUMERIC_ROUNDABORT OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET QUOTED_IDENTIFIER OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET RECURSIVE_TRIGGERS OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET  DISABLE_BROKER<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET AUTO_UPDATE_STATISTICS_ASYNC OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET DATE_CORRELATION_OPTIMIZATION OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET TRUSTWORTHY OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET ALLOW_SNAPSHOT_ISOLATION OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET PARAMETERIZATION SIMPLE<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET READ_COMMITTED_SNAPSHOT OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET HONOR_BROKER_PRIORITY OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET RECOVERY SIMPLE<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET  MULTI_USER<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET PAGE_VERIFY CHECKSUM<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET DB_CHAINING OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET FILESTREAM( NON_TRANSACTED_ACCESS = OFF )<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET TARGET_RECOVERY_TIME = 60 SECONDS<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET DELAYED_DURABILITY = DISABLED<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET QUERY_STORE = OFF<br />
GO</p>
<p>USE [TrialDB]<br />
GO</p>
<p>ALTER DATABASE SCOPED CONFIGURATION SET MAXDOP = 0;<br />
GO</p>
<p>ALTER DATABASE SCOPED CONFIGURATION FOR SECONDARY SET MAXDOP = PRIMARY;<br />
GO</p>
<p>ALTER DATABASE SCOPED CONFIGURATION SET LEGACY_CARDINALITY_ESTIMATION = OFF;<br />
GO</p>
<p>ALTER DATABASE SCOPED CONFIGURATION FOR SECONDARY SET LEGACY_CARDINALITY_ESTIMATION = PRIMARY;<br />
GO</p>
<p>ALTER DATABASE SCOPED CONFIGURATION SET PARAMETER_SNIFFING = ON;<br />
GO</p>
<p>ALTER DATABASE SCOPED CONFIGURATION FOR SECONDARY SET PARAMETER_SNIFFING = PRIMARY;<br />
GO</p>
<p>ALTER DATABASE SCOPED CONFIGURATION SET QUERY_OPTIMIZER_HOTFIXES = OFF;<br />
GO</p>
<p>ALTER DATABASE SCOPED CONFIGURATION FOR SECONDARY SET QUERY_OPTIMIZER_HOTFIXES = PRIMARY;<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET  READ_WRITE<br />
GO<br />
[/sql]</p>
<p><strong>Create a table</strong></p>
<p>To create a table, you can run the query below.</p>
<p>[sql]<br />
USE [TrialDB]<br />
GO</p>
<p>/****** Object:  Table [dbo].[Course]    Script Date: 20-11-2016 03:57:30 PM ******/<br />
SET ANSI_NULLS ON<br />
GO</p>
<p>SET QUOTED_IDENTIFIER ON<br />
GO</p>
<p>CREATE TABLE [dbo].[Course](<br />
	[CourseID] [int] NOT NULL,<br />
	[CourseName] [nvarchar](50) NOT NULL,<br />
	[CourseDescription] [nvarchar](100) NULL,<br />
 CONSTRAINT [PK_Course] PRIMARY KEY CLUSTERED<br />
(<br />
	[CourseID] 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>So our database is ready. Now we will create an Entity Data Model with the database we created.</p>
<div id="attachment_11981" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/12/Create_Entity_data_model.png"><img decoding="async" aria-describedby="caption-attachment-11981" src="http://sibeeshpassion.com/wp-content/uploads/2016/12/Create_Entity_data_model-1024x793.png" alt="create_entity_data_model" width="634" height="491" class="size-large wp-image-11981" srcset="/wp-content/uploads/2016/12/Create_Entity_data_model-1024x793.png 1024w, /wp-content/uploads/2016/12/Create_Entity_data_model-300x232.png 300w, /wp-content/uploads/2016/12/Create_Entity_data_model-768x595.png 768w, /wp-content/uploads/2016/12/Create_Entity_data_model-400x310.png 400w, /wp-content/uploads/2016/12/Create_Entity_data_model-775x600.png 775w, /wp-content/uploads/2016/12/Create_Entity_data_model.png 1158w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-11981" class="wp-caption-text">create_entity_data_model</p></div>
<p><strong>Install Knockout JS</strong></p>
<p>To install Knockout JS in your project, please right click on your project ad click on Manage Nuget Package and search for &#8216;Knockout&#8217;.</p>
<div id="attachment_11982" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/12/Install_Knockout.png"><img decoding="async" aria-describedby="caption-attachment-11982" src="http://sibeeshpassion.com/wp-content/uploads/2016/12/Install_Knockout-1024x592.png" alt="install_knockout" width="634" height="367" class="size-large wp-image-11982" srcset="/wp-content/uploads/2016/12/Install_Knockout-1024x592.png 1024w, /wp-content/uploads/2016/12/Install_Knockout-300x173.png 300w, /wp-content/uploads/2016/12/Install_Knockout-768x444.png 768w, /wp-content/uploads/2016/12/Install_Knockout-400x231.png 400w, /wp-content/uploads/2016/12/Install_Knockout-1038x600.png 1038w, /wp-content/uploads/2016/12/Install_Knockout.png 1485w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-11982" class="wp-caption-text">install_knockout</p></div>
<p>Now let us start our coding as everything is set. </p>
<p><strong>C &#8211; Create Operation</strong></p>
<p>So we are going to see the create operation, as it comes first in CRUD. Let us set up our controller first. You can see the controller code for create operation here.</p>
<p>[csharp]<br />
 // GET: Home/Create<br />
        public ActionResult Create()<br />
        {<br />
            return View();<br />
        }</p>
<p>        // POST: Home/Create<br />
        [HttpPost]<br />
        public string Create(Course course)<br />
        {<br />
            if (!ModelState.IsValid) return &quot;Model is invalid&quot;;<br />
            _db.Courses.Add(course);<br />
            _db.SaveChanges();<br />
            return &quot;Cource is created&quot;;<br />
        }<br />
[/csharp]</p>
<p>Here the first action calls the view for the create operation and the second operation insert the data to database. And _db is our entity.</p>
<p>[csharp]<br />
private readonly TrialDBEntities _db = new TrialDBEntities();<br />
[/csharp]</p>
<p>Now let&#8217;s go ahead and create view for Create operation.</p>
<p>[html]<br />
@model MVCCRUDKnockout.Models.Course</p>
<p>@{<br />
    ViewBag.Title = &quot;Create&quot;;<br />
}</p>
<p>&lt;div class=&quot;form-horizontal&quot;&gt;<br />
    &lt;h4&gt;Course&lt;/h4&gt;<br />
    &lt;hr&gt;</p>
<p>    &lt;div class=&quot;form-group&quot;&gt;<br />
        &lt;label class=&quot;control-label col-md-2&quot; for=&quot;CourseName&quot;&gt;CourseName&lt;/label&gt;<br />
        &lt;div class=&quot;col-md-10&quot;&gt;<br />
            &lt;input class=&quot;form-control text-box single-line&quot; id=&quot;CourseName&quot; name=&quot;CourseName&quot; type=&quot;text&quot; value=&quot;&quot; data-bind=&quot;value: CourseName&quot;&gt;<br />
        &lt;/div&gt;<br />
    &lt;/div&gt;</p>
<p>    &lt;div class=&quot;form-group&quot;&gt;<br />
        &lt;label class=&quot;control-label col-md-2&quot; for=&quot;CourseDescription&quot;&gt;CourseDescription&lt;/label&gt;<br />
        &lt;div class=&quot;col-md-10&quot;&gt;<br />
            &lt;input class=&quot;form-control text-box single-line&quot; id=&quot;CourseDescription&quot; name=&quot;CourseDescription&quot; type=&quot;text&quot; value=&quot;&quot; data-bind=&quot;value: CourseDescription&quot;&gt;<br />
        &lt;/div&gt;<br />
    &lt;/div&gt;</p>
<p>    &lt;div class=&quot;form-group&quot;&gt;<br />
        &lt;div class=&quot;col-md-offset-2 col-md-10&quot;&gt;<br />
            &lt;input type=&quot;button&quot; data-bind=&quot;click: createCourse&quot; value=&quot;Create&quot; class=&quot;btn btn-default&quot;&gt;<br />
        &lt;/div&gt;<br />
    &lt;/div&gt;<br />
&lt;/div&gt;</p>
<p>&lt;div&gt;<br />
    @Html.ActionLink(&quot;Back to List&quot;, &quot;Read&quot;)<br />
&lt;/div&gt;<br />
&lt;script src=&quot;~/Scripts/jquery-1.10.2.min.js&quot;&gt;&lt;/script&gt;<br />
&lt;script src=&quot;~/Scripts/knockout-3.4.0.js&quot;&gt;&lt;/script&gt;<br />
&lt;script src=&quot;~/Scripts/KOScripts/KOCreate.js&quot;&gt;&lt;/script&gt;<br />
[/html]</p>
<p>Did you notice that we are binding data to our input controls as <em>data-bind=&#8221;value: CourseName&#8221;</em>? This value is related to the view model we are going to set, the interesting this is, the values in the model will get changed as you change the values in the input. You don&#8217;t need to add any kind of codes for that operations. </p>
<p>At last we are binding a click event as follows right?</p>
<p>[html]<br />
&lt;input type=&quot;button&quot; data-bind=&quot;click: createCourse&quot; value=&quot;Create&quot; class=&quot;btn btn-default&quot;&gt;<br />
[/html]</p>
<p>This will call the function <em>createCourse</em> which we are going to specify in our view model. Now you may be thinking what is this view model? This knockout uses MVVM pattern and now let us read some basic information provided in <a href="http://knockoutjs.com/documentation/observables.html" target="_blank" rel="noopener">Knockout JS documentation</a>.</p>
<p><strong>MVVM and View Models</strong></p>
<p>Model-View-View Model (MVVM) is a design pattern for building user interfaces. It describes how you can keep a potentially sophisticated UI simple by splitting it into three parts:</p>
<p><em>A model</em>: your application’s stored data. This data represents objects and operations in your business domain (e.g., bank accounts that can perform money transfers) and is independent of any UI. When using KO, you will usually make Ajax calls to some server-side code to read and write this stored model data.</p>
<p><em>A view model</em>: a pure-code representation of the data and operations on a UI. For example, if you’re implementing a list editor, your view model would be an object holding a list of items, and exposing methods to add and remove items.</p>
<p>Note that this is not the UI itself: it doesn’t have any concept of buttons or display styles. It’s not the persisted data model either &#8211; it holds the unsaved data the user is working with. When using KO, your view models are pure JavaScript objects that hold no knowledge of HTML. Keeping the view model abstract in this way lets it stay simple, so you can manage more sophisticated behaviors without getting lost.</p>
<p><em>A view</em>: a visible, interactive UI representing the state of the view model. It displays information from the view model, sends commands to the view model (e.g., when the user clicks buttons), and updates whenever the state of the view model changes.</p>
<p>When using KO, your view is simply your HTML document with declarative bindings to link it to the view model. Alternatively, you can use templates that generate HTML using data from your view model.</p>
<p>Now back to our Create operation, <em>KOCreate.js</em> is the file we are going to write our operation. Now please open that file and bind view model as follows.</p>
<p>[js]<br />
$(function () {<br />
    ko.applyBindings(modelCreate);<br />
});<br />
[/js]</p>
<div id="attachment_11983" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/12/Knockout_apply_bindings-e1481469786202.png"><img decoding="async" aria-describedby="caption-attachment-11983" src="http://sibeeshpassion.com/wp-content/uploads/2016/12/Knockout_apply_bindings-e1481469786202.png" alt="knockout_apply_bindings" width="634" height="100" class="size-full wp-image-11983" srcset="/wp-content/uploads/2016/12/Knockout_apply_bindings-e1481469786202.png 634w, /wp-content/uploads/2016/12/Knockout_apply_bindings-e1481469786202-300x47.png 300w, /wp-content/uploads/2016/12/Knockout_apply_bindings-e1481469786202-400x63.png 400w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-11983" class="wp-caption-text">knockout_apply_bindings</p></div>
<p>Now preceding is our view model and associated functions.</p>
<p>[js]<br />
 var modelCreate = {<br />
    CourseName: ko.observable(),<br />
    CourseDescription: ko.observable(),<br />
    createCourse: function () {<br />
        try {<br />
            $.ajax({<br />
                url: &#8216;/Home/Create&#8217;,<br />
                type: &#8216;post&#8217;,<br />
                dataType: &#8216;json&#8217;,<br />
                data: ko.toJSON(this), //Here the data wil be converted to JSON<br />
                contentType: &#8216;application/json&#8217;,<br />
                success: successCallback,<br />
                error: errorCallback<br />
            });<br />
        } catch (e) {<br />
            window.location.href = &#8216;/Home/Read/&#8217;;<br />
        }<br />
    }<br />
};</p>
<p>function successCallback(data) {<br />
    window.location.href = &#8216;/Home/Read/&#8217;;<br />
}<br />
function errorCallback(err) {<br />
    window.location.href = &#8216;/Home/Read/&#8217;;<br />
}<br />
[/js]</p>
<p>Here <em>ko.observable()</em> are special objects which can notify the changes and update the model accordingly. So if you need to update your UI automatically when the view model changes, you can use <em>observable()</em>.Now please run your view and check whether it is working fine.</p>
<div id="attachment_11984" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/12/Create_Page-e1481470164389.png"><img decoding="async" aria-describedby="caption-attachment-11984" src="http://sibeeshpassion.com/wp-content/uploads/2016/12/Create_Page-e1481470164389.png" alt="create_page" width="634" height="423" class="size-full wp-image-11984" srcset="/wp-content/uploads/2016/12/Create_Page-e1481470164389.png 634w, /wp-content/uploads/2016/12/Create_Page-e1481470164389-300x200.png 300w, /wp-content/uploads/2016/12/Create_Page-e1481470164389-400x267.png 400w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-11984" class="wp-caption-text">create_page</p></div>
<p><strong>R &#8211; Read operation</strong></p>
<p>As we have completed our Create operation, now it is time for Read. Please open your controller and write the actions as follows.</p>
<p>[csharp]<br />
// GET: Home<br />
        public ActionResult Read()<br />
        {<br />
            return View();<br />
        }</p>
<p>        //GET All Courses<br />
        public JsonResult ListCourses()<br />
        {<br />
            return Json(_db.Courses.ToList(), JsonRequestBehavior.AllowGet);<br />
        }<br />
[/csharp]</p>
<p>You can create your Read view as preceding.</p>
<p>[html]<br />
@{<br />
    ViewBag.Title = &quot;Read&quot;;<br />
}</p>
<p>&lt;h2&gt;Index&lt;/h2&gt;</p>
<p>&lt;p&gt;<br />
    @Html.ActionLink(&quot;Create New&quot;, &quot;Create&quot;)<br />
&lt;/p&gt;<br />
&lt;table class=&quot;table&quot;&gt;<br />
    &lt;tr&gt;<br />
        &lt;th&gt;<br />
            Course Name<br />
        &lt;/th&gt;<br />
        &lt;th&gt;<br />
            Course Description<br />
        &lt;/th&gt;<br />
        &lt;th&gt;&lt;/th&gt;<br />
    &lt;/tr&gt;<br />
    &lt;tbody data-bind=&quot;foreach: Courses&quot;&gt;<br />
    &lt;tr&gt;<br />
        &lt;td data-bind=&quot;text: CourseName&quot;&gt;&lt;/td&gt;<br />
        &lt;td data-bind=&quot;text: CourseDescription&quot;&gt;&lt;/td&gt;<br />
        &lt;td&gt;<br />
            &lt;a data-bind=&quot;attr: { &#8216;href&#8217;: &#8216;@Url.Action(&quot;Edit&quot;, &quot;Home&quot;)/&#8217; + CourseID }&quot; class=&quot;btn-link&quot;&gt;Edit&lt;/a&gt;<br />
            &lt;a data-bind=&quot;attr: { &#8216;href&#8217;: &#8216;@Url.Action(&quot;Delete&quot;, &quot;Home&quot;)/&#8217; + CourseID }&quot; class=&quot;btn-link&quot;&gt;Delete&lt;/a&gt;<br />
        &lt;/td&gt;<br />
    &lt;/tr&gt;<br />
    &lt;/tbody&gt;<br />
&lt;/table&gt;<br />
&lt;script src=&quot;~/Scripts/jquery-1.10.2.min.js&quot;&gt;&lt;/script&gt;<br />
&lt;script src=&quot;~/Scripts/knockout-3.4.0.js&quot;&gt;&lt;/script&gt;<br />
&lt;script src=&quot;~/Scripts/KOScripts/KORead.js&quot;&gt;&lt;/script&gt;<br />
[/html]</p>
<p>Here we are using <em>data-bind=&#8221;foreach: Courses&#8221;</em> for looping through our model we are going to create now. So shall we do that? Please create a JS file with name <em>KORead.js</em> and add the following code.</p>
<p>[js]<br />
$(function () {<br />
    ko.applyBindings(modelView);<br />
    modelView.viewCourses();<br />
});</p>
<p>var modelView = {<br />
    Courses: ko.observableArray([]),<br />
    viewCourses: function () {<br />
        var thisObj = this;<br />
        try {<br />
            $.ajax({<br />
                url: &#8216;/Home/ListCourses&#8217;,<br />
                type: &#8216;GET&#8217;,<br />
                dataType: &#8216;json&#8217;,<br />
                contentType: &#8216;application/json&#8217;,<br />
                success: function (data) {<br />
                    thisObj.Courses(data); //Here we are assigning values to KO Observable array<br />
                },<br />
                error: function (err) {<br />
                    alert(err.status + &quot; : &quot; + err.statusText);<br />
                }<br />
            });<br />
        } catch (e) {<br />
            window.location.href = &#8216;/Home/Read/&#8217;;<br />
        }<br />
    }<br />
};<br />
[/js]</p>
<p>Here goes the output.</p>
<div id="attachment_11985" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/12/Read_Page.png"><img decoding="async" aria-describedby="caption-attachment-11985" src="http://sibeeshpassion.com/wp-content/uploads/2016/12/Read_Page-1024x299.png" alt="read_page" width="634" height="185" class="size-large wp-image-11985" srcset="/wp-content/uploads/2016/12/Read_Page-1024x299.png 1024w, /wp-content/uploads/2016/12/Read_Page-300x88.png 300w, /wp-content/uploads/2016/12/Read_Page-768x225.png 768w, /wp-content/uploads/2016/12/Read_Page-400x117.png 400w, /wp-content/uploads/2016/12/Read_Page.png 634w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-11985" class="wp-caption-text">read_page</p></div>
<p>Now it is time for Update operation. Are you ready?</p>
<p><strong>U &#8211; Update operation</strong></p>
<p>As we did for the above two operation, let us create some actions in our controller first. </p>
<p>[csharp]<br />
// GET: Home/Edit/5<br />
        public ActionResult Edit(int? id)<br />
        {<br />
            if (id == null)<br />
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);<br />
            var course = _db.Courses.Find(id);<br />
            if (course == null)<br />
                return HttpNotFound();<br />
            var serializer = new JavaScriptSerializer();<br />
            ViewBag.SelectedCourse = serializer.Serialize(course);<br />
            return View();<br />
        }</p>
<p>        // POST: Home/Update/5<br />
        [HttpPost]<br />
        public string Update(Course course)<br />
        {<br />
            if (!ModelState.IsValid) return &quot;Invalid model&quot;;<br />
            _db.Entry(course).State = EntityState.Modified;<br />
            _db.SaveChanges();<br />
            return &quot;Updated successfully&quot;;<br />
        }<br />
[/csharp]</p>
<p>Here the first action with parameter ID is called whenever a user click on Edit link from the table we created. And we are setting the queried data to <em>ViewBag</em> so that we can use it for our related operation. For now, we can create a view as follows.</p>
<p>[html]<br />
@{<br />
    ViewBag.Title = &quot;Edit&quot;;<br />
}</p>
<p>&lt;h2&gt;Edit&lt;/h2&gt;</p>
<p>@using (Html.BeginForm())<br />
{<br />
    @Html.AntiForgeryToken()</p>
<p>    &lt;div class=&quot;form-horizontal&quot;&gt;<br />
        &lt;h4&gt;Course&lt;/h4&gt;</p>
<p>        &lt;div class=&quot;form-group&quot;&gt;<br />
            &lt;label class=&quot;control-label col-md-2&quot; for=&quot;CourseName&quot;&gt;CourseName&lt;/label&gt;<br />
            &lt;div class=&quot;col-md-10&quot;&gt;<br />
                &lt;input class=&quot;form-control text-box single-line&quot; id=&quot;CourseName&quot; name=&quot;CourseName&quot; type=&quot;text&quot; value=&quot;&quot; data-bind=&quot;value: CourseName&quot;&gt;<br />
            &lt;/div&gt;<br />
        &lt;/div&gt;</p>
<p>        &lt;div class=&quot;form-group&quot;&gt;<br />
            &lt;label class=&quot;control-label col-md-2&quot; for=&quot;CourseDescription&quot;&gt;CourseDescription&lt;/label&gt;<br />
            &lt;div class=&quot;col-md-10&quot;&gt;<br />
                &lt;input class=&quot;form-control text-box single-line&quot; id=&quot;CourseDescription&quot; name=&quot;CourseDescription&quot; type=&quot;text&quot; value=&quot;&quot; data-bind=&quot;value: CourseDescription&quot;&gt;<br />
            &lt;/div&gt;<br />
        &lt;/div&gt;</p>
<p>        &lt;div class=&quot;form-group&quot;&gt;<br />
            &lt;div class=&quot;col-md-offset-2 col-md-10&quot;&gt;<br />
                &lt;input type=&quot;button&quot; data-bind=&quot;click: updateCourse&quot; value=&quot;Update&quot; class=&quot;btn btn-default&quot;&gt;<br />
            &lt;/div&gt;<br />
        &lt;/div&gt;<br />
    &lt;/div&gt;<br />
}<br />
&lt;script type=&quot;text/javascript&quot;&gt;<br />
    var selectedCourse = &#8216;@Html.Raw(ViewBag.selectedCourse)&#8217;;<br />
&lt;/script&gt;<br />
&lt;div&gt;<br />
    @Html.ActionLink(&quot;Back to List&quot;, &quot;Read&quot;)<br />
&lt;/div&gt;<br />
&lt;script src=&quot;~/Scripts/jquery-1.10.2.min.js&quot;&gt;&lt;/script&gt;<br />
&lt;script src=&quot;~/Scripts/knockout-3.4.0.js&quot;&gt;&lt;/script&gt;<br />
&lt;script src=&quot;~/Scripts/KOScripts/KOUpdate.js&quot;&gt;&lt;/script&gt;<br />
[/html]</p>
<p>And create a JS with name <em>KOUpdate.js</em> and add the following code. </p>
<p>[js]<br />
var parsedSelectedCourse = $.parseJSON(selectedCourse);<br />
$(function () {<br />
    ko.applyBindings(modelUpdate);<br />
});</p>
<p>var modelUpdate = {<br />
    CourseID: ko.observable(parsedSelectedCourse.CourseID),<br />
    CourseName: ko.observable(parsedSelectedCourse.CourseName),<br />
    CourseDescription: ko.observable(parsedSelectedCourse.CourseDescription),<br />
    updateCourse: function () {<br />
        try {<br />
            $.ajax({<br />
                url: &#8216;/Home/Update&#8217;,<br />
                type: &#8216;POST&#8217;,<br />
                dataType: &#8216;json&#8217;,<br />
                data: ko.toJSON(this),<br />
                contentType: &#8216;application/json&#8217;,<br />
                success: successCallback,<br />
                error: errorCallback<br />
            });<br />
        } catch (e) {<br />
            window.location.href = &#8216;/Home/Read/&#8217;;<br />
        }<br />
    }<br />
};</p>
<p>function successCallback(data) {<br />
    window.location.href = &#8216;/Home/Read/&#8217;;<br />
}<br />
function errorCallback(err) {<br />
    window.location.href = &#8216;/Home/Read/&#8217;;<br />
}<br />
[/js]</p>
<p>Now, run your application and see the Edit/Update operation.</p>
<div id="attachment_11986" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/12/Edit_Page-e1481471984157.png"><img decoding="async" aria-describedby="caption-attachment-11986" src="http://sibeeshpassion.com/wp-content/uploads/2016/12/Edit_Page-e1481471984157.png" alt="edit_page" width="634" height="432" class="size-full wp-image-11986" srcset="/wp-content/uploads/2016/12/Edit_Page-e1481471984157.png 634w, /wp-content/uploads/2016/12/Edit_Page-e1481471984157-300x204.png 300w, /wp-content/uploads/2016/12/Edit_Page-e1481471984157-320x218.png 320w, /wp-content/uploads/2016/12/Edit_Page-e1481471984157-160x110.png 160w, /wp-content/uploads/2016/12/Edit_Page-e1481471984157-400x273.png 400w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-11986" class="wp-caption-text">edit_page</p></div>
<p><strong>D &#8211; Delete operation</strong></p>
<p>So our last operation, Delete. Let&#8217;s edit our controller as follows. </p>
<p>[csharp]<br />
// GET: Home/Delete/5<br />
        public ActionResult Delete(int? id)<br />
        {<br />
            if (id == null)<br />
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);<br />
            var course = _db.Courses.Find(id);<br />
            if (course == null)<br />
                return HttpNotFound();<br />
            var serializer = new JavaScriptSerializer();<br />
            ViewBag.SelectedCourse = serializer.Serialize(course);<br />
            return View();<br />
        }</p>
<p>        // POST: Home/Delete/5<br />
        [HttpPost, ActionName(&quot;Delete&quot;)]<br />
        public string Delete(Course course)<br />
        {<br />
            if (course == null) return &quot;Invalid data&quot;;<br />
            var getCourse = _db.Courses.Find(course.CourseID);<br />
            _db.Courses.Remove(getCourse);<br />
            _db.SaveChanges();<br />
            return &quot;Deleted successfully&quot;;<br />
        }<br />
[/csharp]</p>
<p>The code looks exactly same as our update operation, so no explanation. Still if you get any issues, please ask. Now let us create our view.</p>
<p>[html]<br />
@model MVCCRUDKnockout.Models.Course</p>
<p>@{<br />
    ViewBag.Title = &quot;Delete&quot;;<br />
}</p>
<p>&lt;h2&gt;Delete&lt;/h2&gt;</p>
<p>&lt;h3&gt;Are you sure you want to delete this?&lt;/h3&gt;<br />
@using (Html.BeginForm())<br />
{<br />
    @Html.AntiForgeryToken()</p>
<p>    &lt;div class=&quot;form-horizontal&quot;&gt;<br />
        &lt;h4&gt;Course&lt;/h4&gt;</p>
<p>        &lt;div class=&quot;form-group&quot;&gt;<br />
            &lt;label class=&quot;control-label col-md-2&quot; for=&quot;CourseName&quot;&gt;CourseName&lt;/label&gt;<br />
            &lt;div class=&quot;col-md-10&quot;&gt;<br />
                &lt;input class=&quot;form-control text-box single-line&quot; id=&quot;CourseName&quot; name=&quot;CourseName&quot; type=&quot;text&quot; value=&quot;&quot; data-bind=&quot;value: CourseName&quot;&gt;<br />
            &lt;/div&gt;<br />
        &lt;/div&gt;</p>
<p>        &lt;div class=&quot;form-group&quot;&gt;<br />
            &lt;label class=&quot;control-label col-md-2&quot; for=&quot;CourseDescription&quot;&gt;CourseDescription&lt;/label&gt;<br />
            &lt;div class=&quot;col-md-10&quot;&gt;<br />
                &lt;input class=&quot;form-control text-box single-line&quot; id=&quot;CourseDescription&quot; name=&quot;CourseDescription&quot; type=&quot;text&quot; value=&quot;&quot; data-bind=&quot;value: CourseDescription&quot;&gt;<br />
            &lt;/div&gt;<br />
        &lt;/div&gt;</p>
<p>        &lt;div class=&quot;form-group&quot;&gt;<br />
            &lt;div class=&quot;col-md-offset-2 col-md-10&quot;&gt;<br />
                &lt;input type=&quot;button&quot; data-bind=&quot;click: deleteCourse&quot; value=&quot;Delete&quot; class=&quot;btn btn-default&quot;&gt;<br />
            &lt;/div&gt;<br />
        &lt;/div&gt;<br />
    &lt;/div&gt;<br />
}<br />
&lt;script type=&quot;text/javascript&quot;&gt;<br />
    var selectedCourse = &#8216;@Html.Raw(ViewBag.selectedCourse)&#8217;;<br />
&lt;/script&gt;<br />
&lt;div&gt;<br />
    @Html.ActionLink(&quot;Back to List&quot;, &quot;Read&quot;)<br />
&lt;/div&gt;<br />
&lt;script src=&quot;~/Scripts/jquery-1.10.2.min.js&quot;&gt;&lt;/script&gt;<br />
&lt;script src=&quot;~/Scripts/knockout-3.4.0.js&quot;&gt;&lt;/script&gt;<br />
&lt;script src=&quot;~/Scripts/KOScripts/KODelete.js&quot;&gt;&lt;/script&gt;<br />
[/html]</p>
<p>And you can always create our knockout codes as preceding.</p>
<p>[js]<br />
var parsedSelectedCourse = $.parseJSON(selectedCourse);<br />
$(function () {<br />
    ko.applyBindings(modelDelete);<br />
});</p>
<p>var modelDelete = {<br />
    CourseID: ko.observable(parsedSelectedCourse.CourseID),<br />
    CourseName: ko.observable(parsedSelectedCourse.CourseName),<br />
    CourseDescription: ko.observable(parsedSelectedCourse.CourseDescription),<br />
    deleteCourse: function () {<br />
        try {<br />
            $.ajax({<br />
                url: &#8216;/Home/Delete&#8217;,<br />
                type: &#8216;POST&#8217;,<br />
                dataType: &#8216;json&#8217;,<br />
                data: ko.toJSON(this),<br />
                contentType: &#8216;application/json&#8217;,<br />
                success: successCallback,<br />
                error: errorCallback<br />
            });<br />
        } catch (e) {<br />
            window.location.href = &#8216;/Home/Read/&#8217;;<br />
        }<br />
    }<br />
};</p>
<p>function successCallback(data) {<br />
    window.location.href = &#8216;/Home/Read/&#8217;;<br />
}<br />
function errorCallback(err) {<br />
    window.location.href = &#8216;/Home/Read/&#8217;;<br />
}<br />
[/js]</p>
<p>If everything goes fine, you will get a page as follows.</p>
<div id="attachment_11987" style="width: 867px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/12/Delete_Page-e1481472332467.png"><img decoding="async" aria-describedby="caption-attachment-11987" src="http://sibeeshpassion.com/wp-content/uploads/2016/12/Delete_Page-e1481472332467.png" alt="delete_page" width="857" height="591" class="size-full wp-image-11987" srcset="/wp-content/uploads/2016/12/Delete_Page-e1481472332467.png 518w, /wp-content/uploads/2016/12/Delete_Page-e1481472332467-300x207.png 300w, /wp-content/uploads/2016/12/Delete_Page-e1481472332467-160x110.png 160w, /wp-content/uploads/2016/12/Delete_Page-e1481472332467-400x276.png 400w" sizes="(max-width: 857px) 100vw, 857px" /></a><p id="caption-attachment-11987" class="wp-caption-text">delete_page</p></div>
<p>That&#8217;s all for today. You can always download the source code attached to see the complete code and application. Happy coding!.</p>
<p><strong>References</strong></p>
<li><a href="http://knockoutjs.com/index.html" target="_blank" rel="noopener">Knockout JS</a></li>
<li><a href="http://knockoutjs.com/documentation/observables.html" target="_blank" rel="noopener">Knockout JS Observables</a></li>
<p><strong>See also</strong></p>
<li><a href="http://knockoutjs.com/documentation/links.html" target="_blank" rel="noopener">External links and tutorials</a></li>
<p><strong>Conclusion</strong></p>
<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>
<p><strong>Your turn. What do you think?</strong></p>
<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://sibeeshpassion.com/mvc-crud-actions-using-knockout-js/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Working With IgniteUI Chart igDataChart Control</title>
		<link>https://sibeeshpassion.com/working-with-igniteui-chart-igdatachart-control/</link>
					<comments>https://sibeeshpassion.com/working-with-igniteui-chart-igdatachart-control/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Thu, 14 Jul 2016 16:10:01 +0000</pubDate>
				<category><![CDATA[Ignite UI]]></category>
		<category><![CDATA[igDataChart]]></category>
		<category><![CDATA[igDataChart In MVC]]></category>
		<category><![CDATA[MVC]]></category>
		<guid isPermaLink="false">http://sibeecst_passion.com/?p=11824</guid>

					<description><![CDATA[In this post we will see how we can use an IgniteUI chart control in our MVC application. If you are new IgniteUI controls I strongly recommend you to read my previous post related to IgniteUI grid here Working With IgniteUI Grid Control. Here we are going to use the chart control available in the kit. We will create an MVC application in Visual Studio. I hope you will like this. Download source code IgniteUI Chart igDataChart Control Background I hope you have already gone though my previous article about IgniteUI grid control. You can consider that as an introduction [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>In this post we will see how we can use an <a href="http://sibeeshpassion.com/category/products/" target="_blank">IgniteUI</a> chart control in our <a href="http://sibeeshpassion.com/category/mvc" target="_blank">MVC</a> application. If you are new IgniteUI controls I strongly recommend you to read my previous post related to IgniteUI grid here <a href="http://sibeeshpassion.com/working-with-igniteui-grid-control/" target="_blank">Working With IgniteUI Grid Control</a>. Here we are going to use the chart control available in the kit. We will create an MVC application in <a href="http://sibeeshpassion.com/category/visual-studio/" target="_blank">Visual Studio</a>. I hope you will like this. </p>
<p><strong>Download source code</strong></p>
<li><a href="https://code.msdn.microsoft.com/Working-With-IgniteUI-a217dad6" target="_blank">IgniteUI Chart igDataChart Control</a></li>
<p><strong>Background</strong></p>
<p>I hope you have already gone though my previous article about <a href="http://sibeeshpassion.com/working-with-igniteui-grid-control/" target="_blank">IgniteUI grid control</a>. You can consider that as an introduction to the control kit. Now as I mentioned, we will try to create a chart using the chart control. Is that fine? </p>
<p><strong>Prerequisites</strong></p>
<p>As I said in the introduction part, we are going to create an IgniteUI grid in MVC application, so you must have a visual studio installed in your machine. </p>
<li>Visual Studio</li>
<li>SQL</li>
<li>IgniteUI control</li>
<p><strong>Table of Contents</strong></p>
<li>Download and install IgniteUI</li>
<li>Set up database</li>
<li>Creating models and entity</li>
<li>Configure MVC application</li>
<li>Creating IgniteUI Chart</li>
<p><strong>Download and install IgniteUI</strong></p>
<p>Please see my <a href="http://sibeeshpassion.com/working-with-igniteui-grid-control/" target="_blank">previous post</a> to see the steps to install the Ignite UI in your machine. </p>
<p><strong>Set up database</strong></p>
<p>[sql]<br />
USE [master]<br />
GO</p>
<p>/****** Object:  Database [TrialsDB]    Script Date: 07/14/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>
<p><strong>Create table with data</strong></p>
<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>
<p><strong>Creating models and entity</strong></p>
<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">here</a>. I have mentioned the steps to be followed in that article. Once you have created the entity, you are good to go.</p>
<p>Here I am assuming that you have created an entity and got a model class as preceding.</p>
<p>[csharp]<br />
//&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;<br />
// &lt;auto-generated&gt;<br />
//     This code was generated from a template.<br />
//<br />
//     Manual changes to this file may cause unexpected behavior in your application.<br />
//     Manual changes to this file will be overwritten if the code is regenerated.<br />
// &lt;/auto-generated&gt;<br />
//&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;</p>
<p>namespace IgniteUI.Models<br />
{<br />
    using System;<br />
    using System.Collections.Generic;</p>
<p>    public partial class Product<br />
    {<br />
        public int ProductID { get; set; }<br />
        public string Name { get; set; }<br />
        public string ProductNumber { get; set; }<br />
        public bool MakeFlag { get; set; }<br />
        public bool FinishedGoodsFlag { get; set; }<br />
        public string Color { get; set; }<br />
        public short SafetyStockLevel { get; set; }<br />
        public short ReorderPoint { get; set; }<br />
        public decimal StandardCost { get; set; }<br />
        public decimal ListPrice { get; set; }<br />
        public string Size { get; set; }<br />
        public string SizeUnitMeasureCode { get; set; }<br />
        public string WeightUnitMeasureCode { get; set; }<br />
        public Nullable&lt;decimal&gt; Weight { get; set; }<br />
        public int DaysToManufacture { get; set; }<br />
        public string ProductLine { get; set; }<br />
        public string Class { get; set; }<br />
        public string Style { get; set; }<br />
        public Nullable&lt;int&gt; ProductSubcategoryID { get; set; }<br />
        public Nullable&lt;int&gt; ProductModelID { get; set; }<br />
        public System.DateTime SellStartDate { get; set; }<br />
        public Nullable&lt;System.DateTime&gt; SellEndDate { get; set; }<br />
        public Nullable&lt;System.DateTime&gt; DiscontinuedDate { get; set; }<br />
        public System.Guid rowguid { get; set; }<br />
        public System.DateTime ModifiedDate { get; set; }<br />
    }<br />
}<br />
[/csharp]</p>
<p><strong>Configure MVC application</strong></p>
<p>As you have finished your installing, we can create a MVC application now. Open your <a href="http://sibeeshpassion.com/category/visual-studio/" target="_blank">Visual Studio</a> and click on new project. Name your project, here I am going to name my project as IgniteUIGrid. Select MVC template and click OK.</p>
<p>Click on the reference and add DLL reference of IgiteUI from C:\Program Files (x86)\Infragistics\2016.1\Ignite UI\MVC\MVC6\Bin\dnx451 or from which ever the folder you installed IgniteUI.</p>
<p><strong>Create controller and actions</strong></p>
<p>Now create a controller as follows.</p>
<p>[csharp]<br />
using System.Web.Mvc;</p>
<p>namespace IgniteUI.Controllers<br />
{<br />
    public class ChartController : Controller<br />
    {<br />
        private IgniteUI.Models.TrialsDBEntities db = new IgniteUI.Models.TrialsDBEntities();</p>
<p>        public ActionResult Index()<br />
        {<br />
            return View();<br />
        }<br />
    }<br />
}<br />
[/csharp]</p>
<p>Now we will create a JsonResult action for fetching the products from database.</p>
<p>[csharp]<br />
[HttpGet]<br />
        public JsonResult Getproducts()<br />
        {<br />
            var model = db.Products.AsQueryable().GroupBy(g =&gt; g.Name, g =&gt; g.ReorderPoint, (key, g) =&gt; new<br />
            {<br />
                Name = key,<br />
                ReorderPoint = g.Take(1)<br />
            }).Take(10);<br />
            return Json(model, JsonRequestBehavior.AllowGet);<br />
        }<br />
[/csharp]</p>
<p>Here I am just grouping the items together and taking the first value for Y axis. And as you know we will we setting &#8216;Name&#8217; as X axis value in chart. </p>
<p>Now shall we create a view?</p>
<p><strong>Create view</strong></p>
<p>[html]<br />
@using Infragistics.Web.Mvc;<br />
@using IgniteUI.Models;<br />
@model IQueryable&lt;IgniteUI.Models.Product&gt;<br />
[/html]</p>
<p><strong>Creating IgniteUI Chart</strong></p>
<p>So our view is ready, now we will create an element where we can render our chart.</p>
<p>[html]<br />
&lt;div style=&quot;width: 100%;&quot;&gt;<br />
    &lt;div id=&quot;chart&quot;&gt;&lt;/div&gt;<br />
&lt;/div&gt;<br />
[/html]</p>
<p>What is next? Yes you are right. We need an ajax call. </p>
<p>[js]<br />
&lt;script&gt;<br />
    $(function () {<br />
        $.ajax({<br />
            type: &#8216;GET&#8217;,<br />
            url: &#8216;http://localhost:39044/chart/Getproducts&#8217;,<br />
            beforeSend: function () {<br />
            },<br />
            success: function (data) {<br />
                GenerateChart(data);<br />
            },<br />
            error: function (e) {<br />
                console.log(&#8216;Error occured: &#8216; + e.message);<br />
            }<br />
        });<br />
    });<br />
&lt;/script&gt;<br />
[/js]</p>
<p>Here <em>GenerateChart</em> is where we actually build our chart.</p>
<p>[js]<br />
 function GenerateChart(chartData) {<br />
        $(&quot;#chart&quot;).igDataChart({<br />
            width: &quot;100%&quot;,<br />
            height: &quot;500px&quot;,<br />
            title: &quot;Product vs Reorder Point&quot;,<br />
            subtitle: &quot;Final products and reorder Point&quot;,<br />
            dataSource: chartData,<br />
            axes: [<br />
                {<br />
                    name: &quot;NameAxis&quot;,<br />
                    type: &quot;categoryX&quot;,<br />
                    title: &quot;Product Name&quot;,<br />
                    label: &quot;Name&quot;<br />
                },<br />
                {<br />
                    name: &quot;YAxisReorderPoint&quot;,<br />
                    type: &quot;numericY&quot;,<br />
                    minimumValue: 0,<br />
                    title: &quot;Reorder Point&quot;,<br />
                }<br />
            ],<br />
            series: [<br />
                {<br />
                    name: &quot;NameReorderPoint&quot;,<br />
                    type: &quot;column&quot;,<br />
                    isHighlightingEnabled: true,<br />
                    isTransitionInEnabled: true,<br />
                    xAxis: &quot;NameAxis&quot;,<br />
                    yAxis: &quot;YAxisReorderPoint&quot;,<br />
                    valueMemberPath: &quot;ReorderPoint&quot;<br />
                }<br />
            ]<br />
        });<br />
    }<br />
[/js]</p>
<p>Go to your shared view folder, open _Layout.cshtml and add the following references to the view.</p>
<p>[html]<br />
 &lt;!&#8211; Ignite UI Required Combined CSS Files &#8211;&gt;<br />
    &lt;link href=&quot;http://cdn-na.infragistics.com/igniteui/2016.1/latest/css/themes/infragistics/infragistics.theme.css&quot; rel=&quot;stylesheet&quot; /&gt;<br />
    &lt;link href=&quot;http://cdn-na.infragistics.com/igniteui/2016.1/latest/css/structure/infragistics.css&quot; rel=&quot;stylesheet&quot; /&gt;<br />
    &lt;!&#8211;CSS file specific for chart styling &#8211;&gt;<br />
    &lt;link href=&quot;http://cdn-na.infragistics.com/igniteui/2016.1/latest/css/structure/modules/infragistics.ui.chart.css&quot; rel=&quot;stylesheet&quot; /&gt;</p>
<p>    &lt;script src=&quot;http://ajax.aspnetcdn.com/ajax/modernizr/modernizr-2.8.3.js&quot;&gt;&lt;/script&gt;<br />
    &lt;script src=&quot;http://code.jquery.com/jquery-1.9.1.min.js&quot;&gt;&lt;/script&gt;<br />
    &lt;script src=&quot;http://code.jquery.com/ui/1.10.3/jquery-ui.min.js&quot;&gt;&lt;/script&gt;</p>
<p>    &lt;!&#8211; Ignite UI Required Combined JavaScript Files &#8211;&gt;<br />
    &lt;script src=&quot;http://cdn-na.infragistics.com/igniteui/2016.1/latest/js/infragistics.core.js&quot;&gt;&lt;/script&gt;<br />
    &lt;script src=&quot;http://cdn-na.infragistics.com/igniteui/2016.1/latest/js/infragistics.lob.js&quot;&gt;&lt;/script&gt;<br />
    &lt;script src=&quot;http://cdn-na.infragistics.com/igniteui/2016.1/latest/js/infragistics.dv.js&quot;&gt;&lt;/script&gt;<br />
[/html]</p>
<p>Now please run your application and go to the <em>http://localhost:39044/Chart</em>, there you can see a chart with the data you have given. </p>
<div id="attachment_11825" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/07/Ignite_UI_Chart_Control.png"><img decoding="async" aria-describedby="caption-attachment-11825" src="http://sibeeshpassion.com/wp-content/uploads/2016/07/Ignite_UI_Chart_Control-1024x446.png" alt="Ignite_UI_Chart_Control" width="634" height="276" class="size-large wp-image-11825" srcset="/wp-content/uploads/2016/07/Ignite_UI_Chart_Control-1024x446.png 1024w, /wp-content/uploads/2016/07/Ignite_UI_Chart_Control-300x131.png 300w, /wp-content/uploads/2016/07/Ignite_UI_Chart_Control-768x335.png 768w, /wp-content/uploads/2016/07/Ignite_UI_Chart_Control-400x174.png 400w, /wp-content/uploads/2016/07/Ignite_UI_Chart_Control.png 634w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-11825" class="wp-caption-text">Ignite_UI_Chart_Control</p></div>
<p>Sounds good? I hope you have got some knowledge about the Ignite UI chart control. That&#8217;s all for today. See you soon with other Ignite UI controls.</p>
<p><strong>Conclusion</strong></p>
<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>
<p><strong>Your turn. What do you think?</strong></p>
<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://sibeeshpassion.com/working-with-igniteui-chart-igdatachart-control/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Fix To: Bundles Are Not Working After Hosting To MVC Application</title>
		<link>https://sibeeshpassion.com/fix-to-bundles-are-not-working-after-hosting-to-mvc-application/</link>
					<comments>https://sibeeshpassion.com/fix-to-bundles-are-not-working-after-hosting-to-mvc-application/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Sun, 24 Apr 2016 00:00:23 +0000</pubDate>
				<category><![CDATA[Azure]]></category>
		<category><![CDATA[Azure Bundle Problem In MVC]]></category>
		<category><![CDATA[Bundle Problem After Publishing]]></category>
		<category><![CDATA[Bundling not working when deployed to web host]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[MVC bundle css not working]]></category>
		<guid isPermaLink="false">http://sibeecst_passion.com/?p=11527</guid>

					<description><![CDATA[In this article we are going to see how we can fix if you are getting some reference errors, or if your bundles are not getting configured properly in your server. I have fixed this issue, and here I am going to share you how you can also fix this error. I hope you will like this. Background Recently I hosted one of my MVC application to Microsoft Azure cloud. And we usually publish our application in release mode right? So here the problem comes. You can replicate the same issue in your local machine itself. Just make the debug [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>In this article we are going to see how we can fix if you are getting some reference errors, or if your bundles are not getting configured properly in your server. I have fixed this issue, and here I am going to share you how you can also fix this error. I hope you will like this.</p>
<p><strong>Background</strong></p>
<p>Recently I hosted one of my MVC application to Microsoft <a href="http://sibeeshpassion.com/category/Azure/" target="_blank">Azure</a> cloud. And we usually publish our application in release mode right? So here the problem comes. You can replicate the same issue in your local machine itself. Just make the debug attribute to false in your Web.config as follows.</p>
<p>[xml]<br />
 &lt;compilation debug=&quot;false&quot; targetFramework=&quot;4.5&quot; /&gt;<br />
[/xml]</p>
<p>And when you run, you will get a prompt as follows. </p>
<div id="attachment_11528" style="width: 602px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/04/Run-without-debugging.png"><img decoding="async" aria-describedby="caption-attachment-11528" src="http://sibeeshpassion.com/wp-content/uploads/2016/04/Run-without-debugging.png" alt="Run without debugging" width="592" height="247" class="size-full wp-image-11528" srcset="/wp-content/uploads/2016/04/Run-without-debugging.png 592w, /wp-content/uploads/2016/04/Run-without-debugging-300x125.png 300w, /wp-content/uploads/2016/04/Run-without-debugging-400x167.png 400w" sizes="(max-width: 592px) 100vw, 592px" /></a><p id="caption-attachment-11528" class="wp-caption-text">Run without debugging</p></div>
<p>Just select Run without debugging option. Now once after your application is run, you can see some script errors in your browser console saying that the references are not loaded correctly. </p>
<div id="attachment_11529" style="width: 660px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/04/Release-more-error-in-console-e1461154379556.png"><img decoding="async" aria-describedby="caption-attachment-11529" src="http://sibeeshpassion.com/wp-content/uploads/2016/04/Release-more-error-in-console-e1461154379556.png" alt="Release more error in console" width="650" height="127" class="size-full wp-image-11529" srcset="/wp-content/uploads/2016/04/Release-more-error-in-console-e1461154379556.png 650w, /wp-content/uploads/2016/04/Release-more-error-in-console-e1461154379556-300x59.png 300w, /wp-content/uploads/2016/04/Release-more-error-in-console-e1461154379556-400x78.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><p id="caption-attachment-11529" class="wp-caption-text">Release more error in console</p></div>
<p>And finally I could find the solution. Here we will see that.</p>
<p><strong>Bundles Are Not Working After Hosting To MVC Application</strong></p>
<p>As I said, the problem is with your bundle config settings. There are few things you must check before going to the last fix. </p>
<li>Please make sure that you have used StyleBundle for creating the style bundle</li>
<li>Please make sure that you have used ScriptBundle for creating the style bundle</li>
<li>Make sure that you are loading the styles using @Styles.Render</li>
<li>Make sure that you are loading the scripts using @Scripts.Render</li>
<li>Make sure that the folder structure is same as you have in local system</li>
<p>If none of the above solution works, you can try the last one. </p>
<li>Make sure that virtual path of bundles doesn&#8217;t contains the folder names you have in your solution</li>
<p>I will explain it. In my case my bundles were as follows. </p>
<p>[html]<br />
 @Styles.Render(&quot;~/Scripts/JQWidgets/CSS&quot;)<br />
 @Scripts.Render(&quot;~/Scripts/JQWidgets&quot;)<br />
[/html]</p>
<p>And I have the folders JQWidgets in my root script folder. This was making the issue. </p>
<div id="attachment_11530" style="width: 275px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/04/Folder-structure.png"><img decoding="async" aria-describedby="caption-attachment-11530" src="http://sibeeshpassion.com/wp-content/uploads/2016/04/Folder-structure.png" alt="Folder structure" width="265" height="114" class="size-full wp-image-11530" /></a><p id="caption-attachment-11530" class="wp-caption-text">Folder structure</p></div>
<p>Now what I did is, I just changed my bundle config settings in <em>BundleConfig.cs</em> as follows(Renaming the folder)</p>
<p>[csharp]<br />
bundles.Add(new ScriptBundle(&quot;~/Scripts/Grid&quot;)<br />
 bundles.Add(new StyleBundle(&quot;~/Scripts/Grid/Styles&quot;)<br />
[/csharp]</p>
<p>And I referenced the same bundles as follows in my views. </p>
<p>[csharp]<br />
 @Styles.Render(&quot;~/Scripts/Grid/Styles&quot;)<br />
@Scripts.Render(&quot;~/Scripts/Grid&quot;)<br />
[/csharp]</p>
<p>Please try these steps and build your application. Once that is done you can publish your application to cloud. I hope this will solve your issue. Have a happy coding.</p>
<p><strong>Conclusion</strong></p>
<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>
<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://sibeeshpassion.com/fix-to-bundles-are-not-working-after-hosting-to-mvc-application/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
			</item>
		<item>
		<title>Web API With HttpClient Or Consume Web API From Console Application</title>
		<link>https://sibeeshpassion.com/web-api-with-httpclient-or-consume-web-api-from-console-application/</link>
					<comments>https://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://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://sibeeshpassion.com/caching-in-web-api/</link>
					<comments>https://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://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://sibeeshpassion.com/angular-js-autocomplete-in-mvc-with-web-api/</link>
					<comments>https://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://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://sibeeshpassion.com/chart-widgets-with-server-side-data-in-mvc-using-angular-js-and-web-api/</link>
					<comments>https://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://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>Custom Deferred Grid Using MVC Web API And Angular JS</title>
		<link>https://sibeeshpassion.com/custom-deferred-grid-using-mvc-web-api-and-angular-js/</link>
					<comments>https://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://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://sibeeshpassion.com/tagit-control-with-data-from-database-using-angular-js-in-mvc-web-api/</link>
					<comments>https://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://sibeeshpassion.com/tagit-control-with-data-from-database-using-angular-js-in-mvc-web-api/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
