<?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://www.sibeeshpassion.com/category/mvc/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.sibeeshpassion.com</link>
	<description>My passion towards life</description>
	<lastBuildDate>Wed, 02 Jun 2021 15:20:02 +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://www.sibeeshpassion.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>LINQ Basic To Advanced &#8211; MVC Demo Application</title>
		<link>https://www.sibeeshpassion.com/linq-basic-to-advanced-mvc-demo-application/</link>
					<comments>https://www.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://www.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://www.sibeeshpassion.com/mvc-crud-actions-using-knockout-js/</link>
					<comments>https://www.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://www.sibeeshpassion.com/mvc-crud-actions-using-knockout-js/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Caching In MVC</title>
		<link>https://www.sibeeshpassion.com/caching-in-mvc/</link>
					<comments>https://www.sibeeshpassion.com/caching-in-mvc/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Sat, 31 Oct 2015 18:25:25 +0000</pubDate>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[Asp.Net]]></category>
		<category><![CDATA[Caching In MVC]]></category>
		<category><![CDATA[CSharp]]></category>
		<category><![CDATA[MVC 4]]></category>
		<category><![CDATA[Output Caching]]></category>
		<category><![CDATA[Performance Improvements In MVC]]></category>
		<guid isPermaLink="false">http://sibeecst_passion.com/?p=10877</guid>

					<description><![CDATA[In this post we will discuss about how we can improve the performance of out MVC application by using the technology Caching . Here I am using Visual Studio 2012. As you all know in MVC it is all about actions, so each and every time we are calling some actions according to the users request. For example when ever a use request a view we will call the controller and get the result and bind the data to the view. Isn&#8217;t it? So what if a user is requesting the same view 50 time in 2 minutes? In normal [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>In this post we will discuss about how we can improve the performance of out MVC application by using the technology <em>Caching </em>. Here I am using Visual Studio 2012. As you all know in MVC it is all about actions, so each and every time we are calling some actions according to the users request. For example when ever a use request a view we will call the controller and get the result and bind the data to the view. Isn&#8217;t it? So what if a user is requesting the same view 50 time in 2 minutes? In normal cases, this won&#8217;t happen, but there are few situations which may be somewhat equal to what I said. In that case it is always recommend to use the most useful thing &#8216;Caching&#8217;. This will make sure that there is no actions which are not required will be happening within a time period. So if a  user already visited the same view within the time periods, the controller action won&#8217;t fire again if user calls the view again. It will return the same view which has been already rendered. Sounds cool? Yes, we will see how we can achieve this!. I hope you will like this.</p>
<p><strong>Background</strong></p>
<p>I am working in a MVC project. As you all know when it comes to performance, our clients will never be satisfied. So we used to everything we have got to improve the performance. One thing we used was Caching. So I thought of writing an article related to that and share wit you all. </p>
<p><strong>What is Caching?</strong></p>
<p>As I said above, it is performance improvement technique where you can get most of. It helps to avoid the unwanted or frequent actions which is already happened just by using Output Caching(In ASP.NET 5 it is ResponseCache). The view which is rendered recently wont fire the controller again if it is in the time limit period, it will just re show the one which is already rendered. It will cache the contents which is returned by the controller action.</p>
<blockquote><p>Imagine that you have a controller which will return your debit/credit transaction from the database. What if the database is normally updating once in a week? Usually when ever a user hits the controller it will hit the DB and fetch the data right? But in this scenario it is not needed to hit the DB again since the data will be same for a week. So we can set the Output Caching so that withing the time interval the controller contents will be in cache so that the view can render the cached data.</p></blockquote>
<p><strong>How to enable Output Caching?</strong></p>
<p>We will create a simple application in Visual Studio first.</p>
<div id="attachment_10879" style="width: 660px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2015/10/Caching_In_MVC-e1446311455769.png"><img decoding="async" aria-describedby="caption-attachment-10879" src="http://sibeeshpassion.com/wp-content/uploads/2015/10/Caching_In_MVC-e1446311455769.png" alt="Caching In MVC" width="650" height="395" class="size-full wp-image-10879" srcset="/wp-content/uploads/2015/10/Caching_In_MVC-e1446311455769.png 650w, /wp-content/uploads/2015/10/Caching_In_MVC-e1446311455769-300x182.png 300w, /wp-content/uploads/2015/10/Caching_In_MVC-e1446311455769-400x243.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><p id="caption-attachment-10879" class="wp-caption-text">Caching In MVC</p></div>
<div id="attachment_10880" style="width: 660px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2015/10/Caching_In_MVC_1-e1446311761707.png"><img decoding="async" aria-describedby="caption-attachment-10880" src="http://sibeeshpassion.com/wp-content/uploads/2015/10/Caching_In_MVC_1-e1446311761707.png" alt="Caching In MVC" width="650" height="589" class="size-full wp-image-10880" srcset="/wp-content/uploads/2015/10/Caching_In_MVC_1-e1446311761707.png 394w, /wp-content/uploads/2015/10/Caching_In_MVC_1-e1446311761707-300x272.png 300w, /wp-content/uploads/2015/10/Caching_In_MVC_1-e1446311761707-400x362.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><p id="caption-attachment-10880" class="wp-caption-text">Caching In MVC</p></div>
<p>Now we will create a control in our MVC application.</p>
<div id="attachment_10881" style="width: 612px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2015/10/Caching_In_MVC_2.png"><img decoding="async" aria-describedby="caption-attachment-10881" src="http://sibeeshpassion.com/wp-content/uploads/2015/10/Caching_In_MVC_2.png" alt="Caching In MVC" width="602" height="392" class="size-full wp-image-10881" srcset="/wp-content/uploads/2015/10/Caching_In_MVC_2.png 602w, /wp-content/uploads/2015/10/Caching_In_MVC_2-300x195.png 300w, /wp-content/uploads/2015/10/Caching_In_MVC_2-400x260.png 400w" sizes="(max-width: 602px) 100vw, 602px" /></a><p id="caption-attachment-10881" class="wp-caption-text">Caching In MVC</p></div>
<p>So our controller is ready, now we need to create simple view and after that we will change our Index action in the controller as below.</p>
<p>[csharp]<br />
public ActionResult Index()<br />
        {<br />
            return Content(DateTime.Now.ToString(&quot;T&quot;));<br />
        }<br />
[/csharp]</p>
<p>So we are returning the current time from the controller. Isn&#8217;t it? Now refresh your view frequently, let us say 2 times in 5 minute, what is the output you are getting?</p>
<div id="attachment_10882" style="width: 318px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2015/10/Caching_In_MVC_3.png"><img decoding="async" aria-describedby="caption-attachment-10882" src="http://sibeeshpassion.com/wp-content/uploads/2015/10/Caching_In_MVC_3.png" alt="Caching In MVC" width="308" height="131" class="size-full wp-image-10882" srcset="/wp-content/uploads/2015/10/Caching_In_MVC_3.png 308w, /wp-content/uploads/2015/10/Caching_In_MVC_3-300x128.png 300w" sizes="(max-width: 308px) 100vw, 308px" /></a><p id="caption-attachment-10882" class="wp-caption-text">Caching In MVC</p></div>
<div id="attachment_10883" style="width: 308px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2015/10/Caching_In_MVC_4.png"><img decoding="async" aria-describedby="caption-attachment-10883" src="http://sibeeshpassion.com/wp-content/uploads/2015/10/Caching_In_MVC_4.png" alt="Caching In MVC" width="298" height="168" class="size-full wp-image-10883" /></a><p id="caption-attachment-10883" class="wp-caption-text">Caching In MVC</p></div>
<p>So have you noticed it within five minutes we have hit the controller twice? Now here is the magic of output cache. Please change your controller code as follows.</p>
<p>[csharp]<br />
[OutputCache(Duration = 300, VaryByParam = &quot;none&quot;)]<br />
        public ActionResult Index()<br />
        {<br />
            return Content(DateTime.Now.ToString(&quot;T&quot;));<br />
        }<br />
[/csharp]</p>
<blockquote><p>Here we are setting the cache duration as 5 minutes (5*60 seconds)</p></blockquote>
<p>Now if you run and do the same exercise you can notice that the controller will be hit only once in 5 minutes duration. That&#8217;s cool right?</p>
<blockquote><p>Even though it is so cook, there is some limitations too. As the memory becomes low, the cache data will be released. So that there won&#8217;t be cached data.</p></blockquote>
<p>Here in our case, we just used a simple view which returns time from the controller. What if the controller has some database operations, for every user&#8217;s hit we need to go to the database right? So in simple words we can say that the caching is helping to reduce the amount of work done must be performed by our web server and database. </p>
<p><strong>So contents are chached. Where?</strong></p>
<p>Now we will see which are all the locations we can save the cache data. Usually the contents are cached in three locations.</p>
<li>Web server</li>
<li>Proxy server</li>
<li>Web browser</li>
<p>You can always set where you want to save the cached data, whether it is in server, client or both server and client by using location property. By default the location will be &#8216;any&#8217;.</p>
<div id="attachment_10884" style="width: 589px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2015/10/Caching_In_MVC_5.png"><img decoding="async" aria-describedby="caption-attachment-10884" src="http://sibeeshpassion.com/wp-content/uploads/2015/10/Caching_In_MVC_5.png" alt="Caching In MVC" width="579" height="332" class="size-full wp-image-10884" srcset="/wp-content/uploads/2015/10/Caching_In_MVC_5.png 579w, /wp-content/uploads/2015/10/Caching_In_MVC_5-300x172.png 300w, /wp-content/uploads/2015/10/Caching_In_MVC_5-400x229.png 400w" sizes="(max-width: 579px) 100vw, 579px" /></a><p id="caption-attachment-10884" class="wp-caption-text">Caching In MVC</p></div>
<p>There are few situations that we should not cache in server. Let me explain, suppose we have a controller which will return the country name of the user logged in to our application. Now I am from &#8216;India&#8217; , so when I logged in to the application it will show the country name as India. That&#8217;s correct. Now have cached these data in the server. So what will happen if a user form Ireland logged in to the application? Will it be good if we show India as his/her country? It doesn&#8217;t make any sense right? </p>
<p>[csharp]<br />
[OutputCache(Duration = 10, VaryByParam = &quot;none&quot;)]<br />
        public ActionResult Index()<br />
        {<br />
            User u = new User();<br />
            return Content(u.getUserCountry());<br />
        }<br />
[/csharp]</p>
<blockquote><p>So in short we can say that we should not cache any personalized data in the server.</p></blockquote>
<p>So what is the fix for this? Simple, cache the data in client. To do that we can change our controller as follows.</p>
<p>[csharp]<br />
[OutputCache(Duration = 10, VaryByParam = &quot;none&quot;, Location=OutputCacheLocation.Client, NoStore=true)]<br />
        public ActionResult Index()<br />
        {<br />
            User u = new User();<br />
            return Content(u.getUserCountry());<br />
        }<br />
[/csharp]</p>
<blockquote><p>To use OutputCacheLocation, you must include the namespace using System.Web.UI;</p></blockquote>
<p>Have you noticed that we have set NoStore=true? This is to intimate the proxy server that should not save any copy of these data in server.</p>
<p><strong>Use of VaryByParam property</strong></p>
<p>Now we are going to discuss an another scenario which explain the use of VaryByParam property. Let us say an action called &#8216;GetEmployee&#8217; which will return all the Employees in our company. Now if we click on any employee links, an another view (GetEmployeeDetails) will show with all the details about that employee( Like account details, leave details, personal informations). So if we save the cached view of GetEmployeeDetails, what will happen? For all the employees, it will show the same GetEmployeeDetails view right?</p>
<p>So we will change the controller actions as follows.</p>
<p>[csharp]<br />
 [OutputCache(Duration = 10, VaryByParam = &quot;none&quot;)]<br />
        public ActionResult GetEmployee()<br />
        {<br />
            Employee e = new Employee();<br />
            return Content(e.getEmployees());<br />
        }<br />
[/csharp]</p>
<p>[csharp]<br />
  [OutputCache(Duration = 10, VaryByParam = &quot;empID&quot;)]<br />
        public ActionResult GetEmployeeDetail(int empID)<br />
        {<br />
            Employee e = new Employee();<br />
            return Content(e.getEmployeeDetails(empID));<br />
        }<br />
[/csharp] </p>
<p>The above mentioned implementation will make sure the different Employee Details view are being generated for different users. Sound cool?</p>
<p><strong>Cache Profiles</strong></p>
<p>There is an another way of achieving the caching, that is cache profiles, which is nothing but creating a tag in web.config file and apply that for different controllers. In this way you can have the same cache profile for different controls. And also it is easy to make any changes in the cache profile since it is just a tag in the web.config file. Any changes in cache profile will get applied easily. I found this is the most effective way of caching. We can do the cache profile as follows.</p>
<p>[html]<br />
&lt;caching&gt;<br />
&lt;outputCacheSettings&gt;<br />
    &lt;outputCacheProfiles&gt;<br />
        &lt;add name=&quot;Admin&quot; duration=&quot;86420&quot; varyByParam=&quot;none&quot;/&gt;<br />
    &lt;/outputCacheProfiles&gt;<br />
&lt;/outputCacheSettings&gt;<br />
&lt;/caching&gt;<br />
[/html]</p>
<p>The above cache profile can be used for any admin control action which will be cached for one day (60*60*24). You can simply use this profile as follows.</p>
<p>[csharp]<br />
[OutputCache(CacheProfile=&quot;Admin&quot;)]<br />
[/csharp]</p>
<p>That is all about the Caching. I will come with an another post which explains caching in ASP.NET 5, MVC 6 soon. Thanks for reading. 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 caching 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’t a blog without comments, but do try to stay on topic. If you have a question unrelated to this post, you’re better off posting it on C# Corner, Code Project, Stack Overflow, Asp.Net Forum instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I can.</p>
<p>Kindest Regards<br />
Sibeesh Venu</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.sibeeshpassion.com/caching-in-mvc/feed/</wfw:commentRss>
			<slash:comments>6</slash:comments>
		
		
			</item>
		<item>
		<title>Load Data From Database Using Web API</title>
		<link>https://www.sibeeshpassion.com/load-data-from-database-using-web-api/</link>
					<comments>https://www.sibeeshpassion.com/load-data-from-database-using-web-api/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Sat, 31 Oct 2015 11:08:57 +0000</pubDate>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[Web API]]></category>
		<category><![CDATA[CRUD in MVC]]></category>
		<category><![CDATA[Load Data From Database Using Web API]]></category>
		<category><![CDATA[MVC4]]></category>
		<category><![CDATA[MVC5]]></category>
		<category><![CDATA[Visual Studio 2013]]></category>
		<guid isPermaLink="false">http://sibeecst_passion.com/?p=10141</guid>

					<description><![CDATA[In this article we will learn about Loading Data From Database in MVC using Web API. We will use Visual Studio 2015 to create a Web API and performs the operations. In this project we are going to create a database and a table called tbl_Subcribers which actually contains a list of data. We will use our normal jQuery ajax to call the Web API, once the data is ready we will format the same in an html table. I hope you will like this. Download the source code Load Data From Database Using Web API Background What is a [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>In this article we will learn about Loading Data From Database in <a href="http://sibeeshpassion.com/tag/mvc/" target="_blank" rel="noopener">MVC </a> using Web API. We will use <a href="http://sibeeshpassion.com/tag/visual-studio/" target="_blank" rel="noopener">Visual Studio</a> 2015 to create a Web API and performs the operations. In this project we are going to create a <em><a href="http://sibeeshpassion.com/tag/database/" target="_blank" rel="noopener"> database </a></em> and a table called <em>tbl_Subcribers</em> which actually contains a list of data. We will use our normal jQuery ajax to call the Web API, once the data is ready we will format the same in an html table. I hope you will like this. </p>
<p><strong>Download the source code</strong></p>
<li><a href="https://code.msdn.microsoft.com/Load-Data-From-Database-59a20734" target="_blank" rel="noopener">Load Data From Database Using Web API</a></li>
<p><strong>Background</strong></p>
<p><em>What is a Web API?</em></p>
<p>A Web API is a kind of a framework which makes building HTTP services easier than ever. It can be used almost everywhere including wide range of clients, mobile devices, browsers etc. It contains normal MVC features like Model, Controller, Actions, Routing etc. Support all HTTP verbs like POST, GET, DELETE, PUT. </p>
<div id="attachment_10874" style="width: 560px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2015/10/Why-Web-API.png"><img decoding="async" aria-describedby="caption-attachment-10874" src="http://sibeeshpassion.com/wp-content/uploads/2015/10/Why-Web-API.png" alt="Why Web API" width="550" height="377" class="size-full wp-image-10874" srcset="/wp-content/uploads/2015/10/Why-Web-API.png 550w, /wp-content/uploads/2015/10/Why-Web-API-300x206.png 300w, /wp-content/uploads/2015/10/Why-Web-API-320x218.png 320w, /wp-content/uploads/2015/10/Why-Web-API-160x110.png 160w, /wp-content/uploads/2015/10/Why-Web-API-400x274.png 400w" sizes="(max-width: 550px) 100vw, 550px" /></a><p id="caption-attachment-10874" class="wp-caption-text">Why Web API</p></div>
<p><em>Image Courtesy : blogs.msdn.com</em></p>
<div id="attachment_10875" style="width: 660px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2015/10/Why-Web-API1-e1446290457816.png"><img decoding="async" aria-describedby="caption-attachment-10875" src="http://sibeeshpassion.com/wp-content/uploads/2015/10/Why-Web-API1-e1446290457816.png" alt="Why Web API" width="650" height="454" class="size-full wp-image-10875" srcset="/wp-content/uploads/2015/10/Why-Web-API1-e1446290457816.png 650w, /wp-content/uploads/2015/10/Why-Web-API1-e1446290457816-300x210.png 300w, /wp-content/uploads/2015/10/Why-Web-API1-e1446290457816-400x279.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><p id="caption-attachment-10875" class="wp-caption-text">Why Web API</p></div>
<p><em>Image Courtesy : forums.asp.net</em></p>
<p><strong>Using the code</strong></p>
<p>We will create our project in Visual Studio 2015. To create a project click File-> New-> Project.</p>
<div id="attachment_10151" style="width: 660px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2015/08/CRUD_in_MVC_Using_Web_API_1-e1440410870120.png"><img decoding="async" aria-describedby="caption-attachment-10151" src="http://sibeeshpassion.com/wp-content/uploads/2015/08/CRUD_in_MVC_Using_Web_API_1-e1440410870120.png" alt="CRUD_in_MVC_Using_Web_API" width="650" height="450" class="size-full wp-image-10151" srcset="/wp-content/uploads/2015/08/CRUD_in_MVC_Using_Web_API_1-e1440410870120.png 650w, /wp-content/uploads/2015/08/CRUD_in_MVC_Using_Web_API_1-e1440410870120-300x208.png 300w, /wp-content/uploads/2015/08/CRUD_in_MVC_Using_Web_API_1-e1440410870120-160x110.png 160w, /wp-content/uploads/2015/08/CRUD_in_MVC_Using_Web_API_1-e1440410870120-400x277.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><p id="caption-attachment-10151" class="wp-caption-text">CRUD_in_MVC_Using_Web_API</p></div>
<div id="attachment_10161" style="width: 660px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2015/08/CRUD_in_MVC_Using_Web_API_2-e1440410926817.png"><img decoding="async" aria-describedby="caption-attachment-10161" src="http://sibeeshpassion.com/wp-content/uploads/2015/08/CRUD_in_MVC_Using_Web_API_2-e1440410926817.png" alt="CRUD_in_MVC_Using_Web_API" width="650" height="590" class="size-full wp-image-10161" srcset="/wp-content/uploads/2015/08/CRUD_in_MVC_Using_Web_API_2-e1440410926817.png 393w, /wp-content/uploads/2015/08/CRUD_in_MVC_Using_Web_API_2-e1440410926817-300x272.png 300w, /wp-content/uploads/2015/08/CRUD_in_MVC_Using_Web_API_2-e1440410926817-400x363.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><p id="caption-attachment-10161" class="wp-caption-text"><br />CRUD_in_MVC_Using_Web_API</p></div>
<p><strong>Create a control</strong></p>
<p>Now we will create a control in our project.</p>
<div id="attachment_10171" style="width: 662px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2015/08/CRUD_in_MVC_Using_Web_API_Adding_Control.png"><img decoding="async" aria-describedby="caption-attachment-10171" src="http://sibeeshpassion.com/wp-content/uploads/2015/08/CRUD_in_MVC_Using_Web_API_Adding_Control.png" alt="CRUD_in_MVC_Using_Web_API_Adding_Control" width="652" height="596" class="size-full wp-image-10171" srcset="/wp-content/uploads/2015/08/CRUD_in_MVC_Using_Web_API_Adding_Control.png 652w, /wp-content/uploads/2015/08/CRUD_in_MVC_Using_Web_API_Adding_Control-300x274.png 300w, /wp-content/uploads/2015/08/CRUD_in_MVC_Using_Web_API_Adding_Control-400x366.png 400w" sizes="(max-width: 652px) 100vw, 652px" /></a><p id="caption-attachment-10171" class="wp-caption-text">CRUD_in_MVC_Using_Web_API_Adding_Control</p></div>
<p>Select <em>Empty API Controller</em> as template.</p>
<div id="attachment_10191" style="width: 648px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2015/08/CRUD_in_MVC_Using_Web_API_Select_APIControl.png"><img decoding="async" aria-describedby="caption-attachment-10191" src="http://sibeeshpassion.com/wp-content/uploads/2015/08/CRUD_in_MVC_Using_Web_API_Select_APIControl.png" alt="CRUD_in_MVC_Using_Web_API_Select_APIControl" width="638" height="430" class="size-full wp-image-10191" srcset="/wp-content/uploads/2015/08/CRUD_in_MVC_Using_Web_API_Select_APIControl.png 638w, /wp-content/uploads/2015/08/CRUD_in_MVC_Using_Web_API_Select_APIControl-300x202.png 300w, /wp-content/uploads/2015/08/CRUD_in_MVC_Using_Web_API_Select_APIControl-400x270.png 400w" sizes="(max-width: 638px) 100vw, 638px" /></a><p id="caption-attachment-10191" class="wp-caption-text">CRUD_in_MVC_Using_Web_API_Select_APIControl</p></div>
<p>As you can notice that we have selected Empty API Controller instead of selecting a normal controller. There are few difference between our normal controller and Empty API Controller. </p>
<p><strong>Controller VS Empty API Controller</strong></p>
<p>A controller normally render your views. But an API controller returns the data which is already serialized. A controller action returns JSON() by converting the data. You can get rid of this by using API controller.</p>
<p>Find out more: <a href="http://stackoverflow.com/questions/9494966/difference-between-apicontroller-and-controller-in-asp-net-mvc" target="_blank" rel="noopener">Controller VS API Controller </a></p>
<p><strong>Create a model</strong></p>
<p>As you all know, we write logic in a class called model in MVC. So next step what we need to do is creating a model. </p>
<p>Right click on Model and click Add new Items and then class. Name it as Subscribers. We are going to handle the subscriber list who all are subscribed to your website.</p>
<p>Now we will create a Database to our application.</p>
<p><strong>Create Database</strong></p>
<div id="attachment_10201" style="width: 660px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2015/08/CRUD_in_MVC_Using_Web_API_Create_Database-e1440412525937.png"><img decoding="async" aria-describedby="caption-attachment-10201" src="http://sibeeshpassion.com/wp-content/uploads/2015/08/CRUD_in_MVC_Using_Web_API_Create_Database-e1440412525937.png" alt="CRUD_in_MVC_Using_Web_API_Create_Database" width="650" height="449" class="size-full wp-image-10201" srcset="/wp-content/uploads/2015/08/CRUD_in_MVC_Using_Web_API_Create_Database-e1440412525937.png 650w, /wp-content/uploads/2015/08/CRUD_in_MVC_Using_Web_API_Create_Database-e1440412525937-300x207.png 300w, /wp-content/uploads/2015/08/CRUD_in_MVC_Using_Web_API_Create_Database-e1440412525937-160x110.png 160w, /wp-content/uploads/2015/08/CRUD_in_MVC_Using_Web_API_Create_Database-e1440412525937-400x276.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><p id="caption-attachment-10201" class="wp-caption-text">CRUD_in_MVC_Using_Web_API_Create_Database</p></div>
<p>Once you created the database, you can see your database in App_Data folder.</p>
<div id="attachment_10211" style="width: 345px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2015/08/CRUD_in_MVC_Using_Web_API_Created_DB.png"><img decoding="async" aria-describedby="caption-attachment-10211" src="http://sibeeshpassion.com/wp-content/uploads/2015/08/CRUD_in_MVC_Using_Web_API_Created_DB.png" alt="CRUD_in_MVC_Using_Web_API_Created_DB" width="335" height="135" class="size-full wp-image-10211" srcset="/wp-content/uploads/2015/08/CRUD_in_MVC_Using_Web_API_Created_DB.png 335w, /wp-content/uploads/2015/08/CRUD_in_MVC_Using_Web_API_Created_DB-300x121.png 300w" sizes="(max-width: 335px) 100vw, 335px" /></a><p id="caption-attachment-10211" class="wp-caption-text">CRUD_in_MVC_Using_Web_API_Created_DB</p></div>
<p>Now will add a new table to our database.</p>
<div id="attachment_10221" style="width: 357px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2015/08/CRUD_in_MVC_Using_Web_API_Adding_Table.png"><img decoding="async" aria-describedby="caption-attachment-10221" src="http://sibeeshpassion.com/wp-content/uploads/2015/08/CRUD_in_MVC_Using_Web_API_Adding_Table.png" alt="CRUD_in_MVC_Using_Web_API_Adding_Table" width="347" height="294" class="size-full wp-image-10221" srcset="/wp-content/uploads/2015/08/CRUD_in_MVC_Using_Web_API_Adding_Table.png 347w, /wp-content/uploads/2015/08/CRUD_in_MVC_Using_Web_API_Adding_Table-300x254.png 300w" sizes="(max-width: 347px) 100vw, 347px" /></a><p id="caption-attachment-10221" class="wp-caption-text">CRUD_in_MVC_Using_Web_API_Adding_Table</p></div>
<p>You can see the query to create a table below. </p>
<p>[sql]<br />
CREATE TABLE [dbo].[Table]<br />
(<br />
	[SubscriberID] INT NOT NULL PRIMARY KEY,<br />
    [MailID] NVARCHAR(50) NOT NULL,<br />
    [SubscribedDate] DATETIME2 NOT NULL<br />
)<br />
[/sql]</p>
<p>It seems our database is ready now. </p>
<div id="attachment_10868" style="width: 271px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2015/10/Load-Data-From-Database-Using-Web-API.png"><img decoding="async" aria-describedby="caption-attachment-10868" src="http://sibeeshpassion.com/wp-content/uploads/2015/10/Load-Data-From-Database-Using-Web-API.png" alt="Load Data From Database Using Web API" width="261" height="293" class="size-full wp-image-10868" /></a><p id="caption-attachment-10868" class="wp-caption-text">Load Data From Database Using Web API</p></div>
<p>The next thing we need to do is to create a ADO.NET Entity Data Model. SO shall we do that? Right click on your model and click on add new item, in the upcoming dialogue, select ADO.NET Entity Data Model.Name that file, Here I have given the name as SP. And in the next steps select the tables, stored procedures, and views you want.</p>
<div id="attachment_10869" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2015/10/Load-Data-From-Database-Using-Web-API-2.png"><img decoding="async" aria-describedby="caption-attachment-10869" src="http://sibeeshpassion.com/wp-content/uploads/2015/10/Load-Data-From-Database-Using-Web-API-2-1024x711.png" alt="Load Data From Database Using Web API " width="634" height="440" class="size-large wp-image-10869" srcset="/wp-content/uploads/2015/10/Load-Data-From-Database-Using-Web-API-2-1024x711.png 1024w, /wp-content/uploads/2015/10/Load-Data-From-Database-Using-Web-API-2-300x208.png 300w, /wp-content/uploads/2015/10/Load-Data-From-Database-Using-Web-API-2-768x533.png 768w, /wp-content/uploads/2015/10/Load-Data-From-Database-Using-Web-API-2-160x110.png 160w, /wp-content/uploads/2015/10/Load-Data-From-Database-Using-Web-API-2-400x278.png 400w, /wp-content/uploads/2015/10/Load-Data-From-Database-Using-Web-API-2-864x600.png 864w, /wp-content/uploads/2015/10/Load-Data-From-Database-Using-Web-API-2.png 1178w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-10869" class="wp-caption-text">Load Data From Database Using Web API</p></div>
<p>So a new file will be created in your model folder. </p>
<p>Now we will create an ajax call so that you can call the web API. We will use normal Ajax with type GET since we need to just retrieve the data.</p>
<blockquote><p> A web API control does not return any action result or any json result, so we need to manually do this. We will use the index.cshtml file as our view</p></blockquote>
<p>We are going to call our web API as follows from the view Index.cshtml.</p>
<p>[js]<br />
 @section scripts<br />
        {<br />
        &lt;script&gt;<br />
            $(document).ready(function () {<br />
                $.ajax(<br />
                    {<br />
                        type: &#8216;GET&#8217;,<br />
                        dataType: &#8216;json&#8217;,<br />
                        contentType: &#8216;application/json;charset=utf-8&#8217;,<br />
                        url: &#8216;http://localhost:3064/api/Subscribers&#8217;,<br />
                        success: function (data) {<br />
                            try {<br />
                                debugger;<br />
                                var html = &#8216;&lt;table&gt;&lt;thead&gt;&lt;th&gt;Mail ID&lt;/th&gt;&lt;th&gt;Subscription ID&lt;/th&gt;&lt;th&gt;Subscription Date&lt;/th&gt;&lt;/thead&gt;&lt;tbody&gt;&#8217;;<br />
                                $.each(data, function (key, val) {<br />
                                    debugger;<br />
                                    html += &#8216;&lt;tr&gt;&lt;td&gt;&#8217;<br />
                                        + &#8216;&lt;a &#8216; + &#8216;href=&quot;mailto:&#8217; + val.MailID + &#8216;&quot;&gt;&#8217; + val.MailID + &#8216;&lt;/a&gt;&#8217; +<br />
                                    &#8216;&lt;/td&gt;&lt;td&gt;&#8217; + val.SubscriberID + &#8216;&lt;/td&gt;&lt;td&gt;&#8217; + val.SubscribedDate + &#8216;&lt;/td&gt;&lt;/tr&gt;&#8217;;<br />
                                });<br />
                                html += &#8216;&lt;/tbody&gt;&lt;/table&gt;&#8217;;<br />
                                $(&#8216;#myGrid&#8217;).html(html);<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 />
                        }</p>
<p>                    }<br />
                    );<br />
            });<br />
        &lt;/script&gt;</p>
<p>    }<br />
[/js]</p>
<p>Once we get the data in the success part of the ajax call we are formulating the data in an HTML table and bind the formatted html to the element myGrid. </p>
<p>[html]<br />
&lt;div id=&quot;myGrid&quot;&gt;&lt;/div&gt;<br />
[/html]</p>
<blockquote><p> Please be noted that url you give must be correct, or else you will end up with some errors. Your actions won&#8217;t work</p></blockquote>
<p>So we are calling our web api as http://localhost:3064/api/Subscribers. Do you remember we have already created a controller? Now we are going back to that. So we need to create an action which returns the total subscribed list from the database, so for that we will write few lines of codes as follows.</p>
<p>[csharp]<br />
public List&lt;tbl_Subscribers&gt; getSubscribers()<br />
        {<br />
            try<br />
            {<br />
                using (var db = new sibeeshpassionEntities())<br />
                {<br />
                    Subscriber sb = new Subscriber();<br />
                    return (sb.getSubcribers(db).ToList());<br />
                }</p>
<p>            }<br />
            catch (Exception)<br />
            {</p>
<p>                throw;<br />
            }<br />
        }<br />
[/csharp]</p>
<p>Here Subscriber is our model class, to get the reference of your model class in controller, you need to include the model namespace. We are getting a list of data in tbl_Subcribers type. Now we will concentrate on model class. </p>
<p>You can see the model action codes here.</p>
<p>[csharp]<br />
 public List&lt;tbl_Subscribers&gt; getSubcribers(sibeeshpassionEntities sb)<br />
        {<br />
            try<br />
            {<br />
                if (sb != null)<br />
                {<br />
                    return sb.tbl_Subscribers.ToList();<br />
                }<br />
                return null;<br />
            }<br />
            catch (Exception)<br />
            {<br />
                throw;<br />
            }<br />
        }<br />
[/csharp]</p>
<p>This will return the data which is available in the table tbl_Subcribers in sibeeshpassion DB. It seems everything is set. Now what else we need to do? Yes we need to create some entries in the table. Please see the insertion query here.</p>
<p>[sql]<br />
INSERT INTO [dbo].[tbl_Subscribers] ([SubscriberID], [MailID], [SubscribedDate]) VALUES (1, N&#8217;sibikv4u@gmail.com&#8217;, N&#8217;2015-10-30 00:00:00&#8242;)<br />
INSERT INTO [dbo].[tbl_Subscribers] ([SubscriberID], [MailID], [SubscribedDate]) VALUES (2, N&#8217;sibeesh.venu@gmail.com&#8217;, N&#8217;2015-10-29 00:00:00&#8242;)<br />
INSERT INTO [dbo].[tbl_Subscribers] ([SubscriberID], [MailID], [SubscribedDate]) VALUES (3, N&#8217;ajaybhasy@gmail.com&#8217;, N&#8217;2015-10-28 00:00:00&#8242;)<br />
[/sql]</p>
<p>So the data is inserted. Isn&#8217;t it?</p>
<div id="attachment_10870" style="width: 527px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2015/10/Load-Data-From-Database-Using-Web-API-3.png"><img decoding="async" aria-describedby="caption-attachment-10870" src="http://sibeeshpassion.com/wp-content/uploads/2015/10/Load-Data-From-Database-Using-Web-API-3.png" alt="Load Data From Database Using Web API " width="517" height="200" class="size-full wp-image-10870" srcset="/wp-content/uploads/2015/10/Load-Data-From-Database-Using-Web-API-3.png 517w, /wp-content/uploads/2015/10/Load-Data-From-Database-Using-Web-API-3-300x116.png 300w, /wp-content/uploads/2015/10/Load-Data-From-Database-Using-Web-API-3-400x155.png 400w" sizes="(max-width: 517px) 100vw, 517px" /></a><p id="caption-attachment-10870" class="wp-caption-text">Load Data From Database Using Web API</p></div>
<blockquote><p><strong>Do you know?</strong><br />
Like we have RouteConfig.cs in MVC, we have another class file called WebApiConfig.cs in Web API which actually sets the routes.</p>
<p>[csharp]<br />
routes.MapRoute(<br />
                name: &quot;Default&quot;,<br />
                url: &quot;{controller}/{action}/{id}&quot;,<br />
                defaults: new { controller = &quot;Home&quot;, action = &quot;Index&quot;, id = UrlParameter.Optional }<br />
            );<br />
[/csharp]
</p></blockquote>
<p>So shall we run our project and see the output? Before going to run, I suggest you to style the HTML table by applying some CSSs as follows.</p>
<p>[css]<br />
&lt;style&gt;<br />
        table,tr,td,th {<br />
            border:1px solid #ccc;<br />
            border-radius:5px;<br />
            padding:10px;<br />
            margin:10px;<br />
        }</p>
<p>    &lt;/style&gt;<br />
[/css]</p>
<p>If everything goes fine, you will get the output as follows.</p>
<div id="attachment_10871" style="width: 660px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2015/10/Load-Data-From-Database-Using-Web-API-4-e1446288898428.png"><img decoding="async" aria-describedby="caption-attachment-10871" src="http://sibeeshpassion.com/wp-content/uploads/2015/10/Load-Data-From-Database-Using-Web-API-4-e1446288898428.png" alt="Load Data From Database Using Web API" width="650" height="497" class="size-full wp-image-10871" srcset="/wp-content/uploads/2015/10/Load-Data-From-Database-Using-Web-API-4-e1446288898428.png 650w, /wp-content/uploads/2015/10/Load-Data-From-Database-Using-Web-API-4-e1446288898428-300x229.png 300w, /wp-content/uploads/2015/10/Load-Data-From-Database-Using-Web-API-4-e1446288898428-400x306.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><p id="caption-attachment-10871" class="wp-caption-text">Load Data From Database Using Web API</p></div>
<p>That is all. We did it. 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’t a blog without comments, but do try to stay on topic. If you have a question unrelated to this post, you’re better off posting it on C# Corner, Code Project, Stack Overflow, Asp.Net Forum instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I can.</p>
<p>Kindest Regards<br />
Sibeesh Venu</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.sibeeshpassion.com/load-data-from-database-using-web-api/feed/</wfw:commentRss>
			<slash:comments>11</slash:comments>
		
		
			</item>
		<item>
		<title>Create And Consume A User Control In MVC</title>
		<link>https://www.sibeeshpassion.com/create-and-consume-a-user-control-in-mvc/</link>
					<comments>https://www.sibeeshpassion.com/create-and-consume-a-user-control-in-mvc/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Tue, 14 Jul 2015 14:13:32 +0000</pubDate>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[Consume User Controls In MVC]]></category>
		<category><![CDATA[Create Controls in MVC]]></category>
		<category><![CDATA[Create User Controls]]></category>
		<category><![CDATA[MVC View]]></category>
		<category><![CDATA[Razor]]></category>
		<category><![CDATA[Use User Controls In MVC]]></category>
		<category><![CDATA[User Controls]]></category>
		<guid isPermaLink="false">http://sibeecst_passion.com/?p=7031</guid>

					<description><![CDATA[Introduction In this article we will learn how we can create and consume a user control in MVC. I hope you will like it. Background Today I got a requirement of working with CellSetGrid. Since it is supported with our normal Asp.Net web pages alone, I was in a need to convert the same to a user view control and consume it in MVC because my application is in MVC4. I have done the same. So I thought of sharing you that with you all. Using the code To do so, You need to follow the following steps. Add reference [&#8230;]]]></description>
										<content:encoded><![CDATA[<p><strong>Introduction</strong></p>
<p>In this article we will learn how we can create and consume a user control in MVC. I hope you will like it.</p>
<p><strong>Background</strong></p>
<p>Today I got a requirement of working with <em>CellSetGrid</em>. Since it is supported with our normal Asp.Net web pages alone, I was in a need to convert the same to a user view control and consume it in MVC because my application is in MVC4. I have done the same. So I thought of sharing you that with you all.</p>
<p><strong>Using the code</strong></p>
<p>To do so, You need to follow the following steps.</p>
<p><em>Add reference to your control DLL</em></p>
<p><img decoding="async" src="http://sibeeshpassion.com/content/images/CreateAndUseAUserControlInMVC1new.png" alt="Create And Consume A User Control In MVC"/></p>
<p><img decoding="async" src="http://sibeeshpassion.com/content/images/CreateAndUseAUserControlInMVC2.png" alt="Create And Consume A User Control In MVC"/></p>
<p><em>Add new Web User Control</em></p>
<p><img decoding="async" src="http://sibeeshpassion.com/content/images/CreateAndUseAUserControlInMVC3.png" alt="Create And Consume A User Control In MVC"/></p>
<p><img decoding="async" src="http://sibeeshpassion.com/content/images/CreateAndUseAUserControlInMVC4.png" alt="Create And Consume A User Control In MVC"/></p>
<p><em>Register your DLL reference</em></p>
<p>[html]<br />
&lt;%@ Register assembly=&quot;CellSetGrid2&quot; namespace=&quot;OLAPControls&quot; tagprefix=&quot;cc1&quot; %&gt;<br />
[/html]</p>
<p><em>Place your control</em></p>
<p>[html]<br />
 &lt;div&gt;<br />
        &lt;cc1:CellSetGrid2 id=&quot;csg2&quot; runat=&quot;server&quot; connectionstring=&quot;Data Source=&quot;Your DataSource&quot;; Initial Catalog =Your DB Name&quot;<br />
            cube=&quot;Your Cube Name&quot; height=&quot;800px&quot; width=&quot;1500px&quot; /&gt;<br />
&lt;/div&gt;<br />
[/html]</p>
<p><em>Change default namespace</em></p>
<p>Go to <em>ADODMGrid.ascx.cs</em> from the solution explorer.</p>
<p><img decoding="async" src="http://sibeeshpassion.com/content/images/CreateAndUseAUserControlInMVC8.png" alt="Create And Consume A User Control In MVC"/></p>
<p>Change Namespace <em>System.Web.UI.UserControl</em> to <em>System.Web.Mvc.ViewUserControl</em></p>
<p><em>Create Controller</em></p>
<p><img decoding="async" src="http://sibeeshpassion.com/content/images/CreateAndUseAUserControlInMVC5.png" alt="Create And Consume A User Control In MVC"/></p>
<p><em>Create a View</em></p>
<p><img decoding="async" src="http://sibeeshpassion.com/content/images/CreateAndUseAUserControlInMVC6.png" alt="Create And Consume A User Control In MVC"/></p>
<p>Please make sure that you have selected a partial view </p>
<p><img decoding="async" src="http://sibeeshpassion.com/content/images/CreateAndUseAUserControlInMVC7.png" alt="Create And Consume A User Control In MVC"/></p>
<p><em>Add the User Control to your View</em></p>
<p>[html]<br />
@Html.Partial(&quot;ADODMGrid&quot;)<br />
@* Here ADODMGrid is our user control name. No need to give its extension (ascx)*@<br />
[/html]</p>
<p>So here we are add our new web user control to our view. </p>
<p><em>Add tagPrefix to your Web.Config</em></p>
<p>Last but the least, you need to add tagPrefix to your web.config file as follows.</p>
<p>[html]<br />
 &lt;controls&gt;<br />
        &lt;add tagPrefix=&quot;cc1&quot; namespace=&quot;OLAPControls&quot; assembly=&quot;CellSetGrid2, Culture=neutral, PublicKeyToken=null&quot; /&gt;<br />
      &lt;/controls&gt;<br />
[/html]</p>
<p>You need to add teh above code under <em>system.web</em> &#8211;> <em>Pages</em></p>
<p>Now if your your view, you can see your control there 🙂</p>
<p><strong>Conclusion</strong></p>
<p>That is all. I hope you liked this article. Please share me your feedback.</p>
<p>Kindest Regards<br />
<a href="http://sibeeshpassion.com/" target="_blank" rel="noopener">Sibeesh Venu</a></p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.sibeeshpassion.com/create-and-consume-a-user-control-in-mvc/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
		<item>
		<title>Uploading and Downloading in MVC Step-by-Step</title>
		<link>https://www.sibeeshpassion.com/uploading-and-downloading-in-mvc-step-by-step/</link>
					<comments>https://www.sibeeshpassion.com/uploading-and-downloading-in-mvc-step-by-step/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Sun, 14 Jun 2015 01:00:52 +0000</pubDate>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[CodeProject]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Download in MVC]]></category>
		<category><![CDATA[File Downloading Using MVC]]></category>
		<category><![CDATA[File Uploading Using MVC]]></category>
		<category><![CDATA[Model View Controller]]></category>
		<category><![CDATA[MVC Download]]></category>
		<category><![CDATA[MVC Upload]]></category>
		<category><![CDATA[Upload in MVC]]></category>
		<guid isPermaLink="false">https://sibeeshpassion.com/?p=1931</guid>

					<description><![CDATA[Introduction I hope you all are fine. Today we will learn how to perform upload and download operations in MVC. Please refer to the step-by-step approach in learning Model View Controller if you are new to MVC. Our MVC Master, Shivprasad koirala has explained the concepts in a perfect way. Download the source code Uploading and Downloading in MVC Step-by-Step Background Some days earlier, I got a requirement to develop a upload and download mechanism in my MVC application. After completing it perfectly, I decided to share it with you all. Using the code Before moving further into the details, [&#8230;]]]></description>
										<content:encoded><![CDATA[<p><strong>Introduction</strong></p>
<p>I hope you all are fine. Today we will learn how to perform upload and download operations in MVC. Please refer to the <a href="http://www.codeproject.com/Articles/207797/Learn-MVC-Model-View-Controller-step-by-step-in" target="_blank" rel="noopener">step-by-step approach</a> in learning Model View Controller if you are new to MVC. Our MVC Master, Shivprasad koirala has explained the concepts in a perfect way.</p>
<p><strong>Download the source code</strong></p>
<li><a href="https://code.msdn.microsoft.com/Uploading-and-Downloading-7b5277ef" target="_blank" rel="noopener">Uploading and Downloading in MVC Step-by-Step</a></li>
<p><strong>Background </strong></p>
<p>Some days earlier, I got a requirement to develop a upload and download mechanism in my MVC application. After completing it perfectly, I decided to share it with you all.</p>
<p><strong>Using the code</strong></p>
<p>Before moving further into the details, let us first list the key points we will explain in this article:</p>
<li>Create a MVC application.</li>
<li>Create a controller.</li>
<li>Create View depending on the controller.</li>
<li>Change the RouteConfig as needed.</li>
<li>Create ActionResult for the actions.</li>
<li>Create a folder where we need to save the downloaded files.</li>
<p>Let us start with creating a controller called “myAction”.<br />
[csharp]<br />
using System;<br />
using System.Collections.Generic;<br />
using System.IO;<br />
using System.Linq;<br />
using System.Web;<br />
using System.Web.Mvc;<br />
namespace UploadDownloadInMVC.Controllers<br />
{<br />
    public class myActionController : Controller<br />
    {<br />
        //<br />
        // GET: /myAction/<br />
    }<br />
}<br />
[/csharp]</p>
<p>As you can see that the controller is empty; we will be writing the action results next.<br />
[csharp]<br />
public ActionResult Index()<br />
       {<br />
           foreach (string upload in Request.Files)<br />
           {<br />
               if (Request.Files[upload].FileName != “”)<br />
               {<br />
                   string path = AppDomain.CurrentDomain.BaseDirectory + “/App_Data/uploads/”;<br />
                   string filename = Path.GetFileName(Request.Files[upload].FileName);<br />
                   Request.Files[upload].SaveAs(Path.Combine(path, filename));<br />
               }<br />
           }<br />
           return View(“Upload”);<br />
       }<br />
[/csharp]</p>
<p>The action result shown above is for index. So, whenever the application loads, the action result will be fired. For that, the following changes should be done for RouteCofig.<br />
[csharp]<br />
public class RouteConfig<br />
    {<br />
        public static void RegisterRoutes(RouteCollection routes)<br />
        {<br />
            routes.IgnoreRoute(“{resource}.axd/{*pathInfo}”);<br />
            routes.MapRoute(<br />
                name: “Default”,<br />
                url: “{controller}/{action}/{id}”,<br />
                defaults: new { controller = “myAction”, action = “Index”, id = UrlParameter.Optional }<br />
            );<br />
        }<br />
    }<br />
[/csharp]</p>
<p>As you can see in the Index Action,  we are checking whether the request parameter contains the files. If it exists, we will save the selected file to the directory</p>
<p><em>/App_Data/uploads/</em> (that we need to manually create in our application). After returning to the view Upload, we need to set the Upload view.</p>
<p><strong>Upload View</strong></p>
<p>The following is the code for the Upload view.<br />
[html]<br />
@{<br />
    ViewBag.Title = “Upload”;<br />
}<br />
&lt;h2&gt;Upload&lt;/h2&gt;<br />
&lt;script src=“~/Scripts/jquery-1.11.1.min.js”&gt;&lt;/script&gt;<br />
&lt;script&gt;<br />
    $(document).ready(function () {<br />
        $(‘#btnUploadFile’).on(‘click’, function () {<br />
            var data = new FormData();<br />
            var files = $(“#fileUpload”).get(0).files;<br />
            // Add the uploaded image content to the form data collection<br />
            if (files.length &gt; 0) {<br />
                data.append(“UploadedImage”, files[0]);<br />
            }<br />
            // Make Ajax request with the contentType = false, and procesDate = false<br />
            var ajaxRequest = $.ajax({<br />
                type: “POST”,<br />
                url: “myAction/Index”,<br />
                contentType: false,<br />
                processData: false,<br />
                data: data<br />
            });<br />
            ajaxRequest.done(function (xhr, textStatus) {<br />
                // Do other operation<br />
            });<br />
        });<br />
    });<br />
&lt;/script&gt;<br />
&lt;input type=“file” name=“FileUpload1″ id=“fileUpload” /&gt;&lt;br /&gt;<br />
&lt;input id=“btnUploadFile” type=“button” value=“Upload File” /&gt;<br />
@Html.ActionLink(“Documents”, “Downloads”)<br />
[/html]</p>
<p>In the upload view, we have the following:</p>
<li>File uploader</li>
<li>Upload button</li>
<li>Ajax call to the controller ( myAction/Index)</li>
<p>Here, we are adding the uploaded image content to the form data collection.<br />
[csharp]<br />
var data = new FormData();<br />
           var files = $(“#fileUpload”).get(0).files;<br />
           // Add the uploaded image content to the form data collection<br />
           if (files.length &gt; 0) {<br />
               data.append(“UploadedImage”, files[0]);<br />
           }<br />
[/csharp]</p>
<p>Once the data is added to the form data collection, we will pass the data to the controller via ajax call. Sounds cool, right? If the procedure goes well, we will see the output as follows.</p>
<p><img decoding="async" src="http://www.c-sharpcorner.com/UploadFile/65794e/uploading-and-downloading-in-mvc/Images/upload1.PNG" alt="" /></p>
<p><img decoding="async" src="http://www.c-sharpcorner.com/UploadFile/65794e/uploading-and-downloading-in-mvc/Images/upload2.PNG" alt="" /></p>
<p>When you choose the file and click upload, your selected file will be uploaded to the folder “uploads” as we have set it in the controller.</p>
<p>We have finished the process of uploading files. We will now move to the downloading section. This is the right time to add the remaining actions to our controller. The following is the code.<br />
[csharp]<br />
public ActionResult Downloads()<br />
        {<br />
            var dir = new System.IO.DirectoryInfo(Server.MapPath(“~/App_Data/uploads/”));<br />
            System.IO.FileInfo[] fileNames = dir.GetFiles(“*.*”); List&lt;string&gt; items = new List&lt;string&gt;();<br />
            foreach (var file in fileNames)<br />
            {<br />
                items.Add(file.Name);<br />
            }<br />
            return View(items);<br />
        }<br />
        public FileResult Download(string ImageName)<br />
        {<br />
            var FileVirtualPath = “~/App_Data/uploads/” + ImageName;<br />
            return File(FileVirtualPath, “application/force-download”, Path.GetFileName(FileVirtualPath));<br />
        }<br />
[/csharp]</p>
<p>Do you remember that we have set an action link in the “Upload” View?<br />
[html]<br />
@Html.ActionLink(“Documents”, “Downloads”)<br />
[/html]</p>
<p>Next, if we click on the “Documents” link, our Action Result Downloads will be fired, right? Now, the following code will explain what is happening here.<br />
[csharp]<br />
var dir = new System.IO.DirectoryInfo(Server.MapPath(“~/App_Data/uploads/”));<br />
            System.IO.FileInfo[] fileNames = dir.GetFiles(“*.*”); List&lt;string&gt; items = new List&lt;string&gt;();<br />
            foreach (var file in fileNames)<br />
            {<br />
                items.Add(file.Name);<br />
            }<br />
            return View(items);<br />
[/csharp]</p>
<p>We are considering all the attached files, adding the file information to a list and returning this list to the view “Download”. Next, here’s the need to set another view. The following code is for the Download View.</p>
<p><strong>Download View</strong><br />
[html]<br />
@{<br />
    ViewBag.Title = “Downloads”;<br />
}<br />
&lt;h2&gt;Downloads&lt;/h2&gt;<br />
@model List&lt;string&gt;<br />
&lt;h2&gt;Downloads&lt;/h2&gt;<br />
&lt;table&gt;<br />
    &lt;tr&gt;<br />
        &lt;th&gt;File Name&lt;/th&gt;<br />
        &lt;th&gt;Link&lt;/th&gt;<br />
    &lt;/tr&gt;<br />
    @for (var i = 0; i &lt;= Model.Count – 1; i++)<br />
    {<br />
        &lt;tr&gt;<br />
            &lt;td&gt;@Model[i].ToString() &lt;/td&gt;<br />
            &lt;td&gt;@Html.ActionLink(“Download”, “Download”, new { ImageName = @Model[i].ToString() }) &lt;/td&gt;<br />
        &lt;/tr&gt;<br />
    }<br />
&lt;/table&gt;<br />
[/html]</p>
<p>Here, we are taking the information (that we are sending from the controller) about the uploaded files and creating the Html.ActionLinks dynamically.</p>
<p>Please note that we are adding the Image name to the  action. Here is the output after performing the operations.</p>
<p><img decoding="async" src="http://www.c-sharpcorner.com/UploadFile/65794e/uploading-and-downloading-in-mvc/Images/downloadWithframe.png" alt="" /></p>
<p>As in the preceding image, when you mouse over the link, it will show the image name along with the controller URL. Click on the link to download the file. So simple, right?</p>
<p><strong>Conclusion</strong></p>
<p>I hope you liked the article. Please provide your valuable feedback; it matters a lot. You can download the source code to determine more.</p>
<p><strong>Point of interest</strong></p>
<p>MVC, MVC Upload, MVC Download, File Uploading Using MVC, File Downloading Using MVC</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.sibeeshpassion.com/uploading-and-downloading-in-mvc-step-by-step/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
