<?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 CRUD &#8211; Sibeesh Passion</title>
	<atom:link href="https://www.sibeeshpassion.com/tag/mvc-crud/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:19:41 +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 CRUD &#8211; Sibeesh Passion</title>
	<link>https://www.sibeeshpassion.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<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 fetchpriority="high" 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>
	</channel>
</rss>
