I) Introduction

I have been browsing multiple sites to check if I could find a complete end to end tutorial or article upon CRUD operations using Knockout.JS and MVC 4. Unfortunately, all the ones I found were incomplete or had too short an explanation. In my last article we learned CRUD in ASP.NET web forms using MVC and EntityFramework. This article is the continuation to the same series. This article will be a kind of tutorial to explain how we can set up a Knockout.JS environment in an MVC4 application that is also capable of performing CRUD operations.

II) Our Road-Map

Part 2: Complete end to end CRUD operations using Knockout.JS and Entity Framework in MVC4 application.

III) Part2: Complete end to end CRUD operations using Knockout.JS and Entity Framework in MVC4 application

We’ll continue to discuss KO step by step in this article

Creating an MVC application.

Creating CRUD action methods using Entity Framework 5.

Perform CRUD operations using MVC4 and Entity Framework 5

Adding Knockout.JS to our MVC application.

Perform CRUD operation using KO in our MVC 4 application.

Before we start, not going very deep into theory I would like to give an introduction to MVC,Entity Framework and Knockout.

IV) MVC

Model: The business entity on which the overall application operates. Many applications use a persistent storage mechanism (such as a database) to store data. MVC does not specifically mention the data access layer because it is understood to be encapsulated by the Model.

View: The user interface that renders the model into a form of interaction.

Controller: Handles a request from a view and updates the model that results a change in Model’s state.

To implement MVC in .NET we need mainly three classes (View, Controller and the Model).

V) Entity Framework

Let’s have a look on standard definition of Entity Framework given by Microsoft:

"The Microsoft ADO.NET Entity Framework is an Object/Relational Mapping (ORM) framework that enables developers to work with relational data as domain-specific objects, eliminating the need for most of the data access plumbing code that developers usually need to write. Using the Entity Framework, developers issue queries using LINQ, then retrieve and manipulate data as strongly typed objects. The Entity Framework’s ORM implementation provides services like change tracking, identity resolution, lazy loading, and query translation so that developers can focus on their application-specific business logic rather than the data access fundamentals."

In a simple language, Entity framework is an Object/Relational Mapping (ORM) framework. It is an enhancement to ADO.NET, an upper layer to ADO.NET that gives developers an automated mechanism for accessing & storing the data in the database.

Hope this gives a glimpse of an ORM and EntityFramework.

VI) Knockout.JS

Knockout.JS (KO) is basically a JS library that enables Declarative Bindings using an ‘Observable’ View Model on the client (browser) following observer pattern approach, enabling UI to bind and refresh itself automatically whenever the data bound is modified. Knockout.JS provides its own templating pattern that helps us to bind our view model data easily. KO works on MVVM pattern i.e. Model-View-View Model.

As the architecture is shown, Views interact with View Models in a two way binding manner i.e. when the model is changed it view updates itself and when view is updated, the model updates itself instantaneously.

KO provides 3 most important features like,

The whole idea of KO derives from these three major functionalities. KO also helps in developing Single page applications (SPA’s).SPA’s are out of the box new way of developing rich internet applications(RIA’s) in todays era.

VII) Application Architecture

The architecture is very much self explanatory. The application works on client-server model, where our MVC application or Web API application (not covered in this tutorial) will interact with EntityFramework layer on server side. Entity Framework layer will be responsible for data transactions with data base.

On client side we have HTML templates which will communicate with server through Ajax calls and the templates will be bind to data via JSON objects through knockout observables (already discussed in first part).

VIII) MVC Application

1. Step1: Create a data base named LearningKO and add a table named student to it, script of the table is as follows,

Step2: Open your Visual Studio (Visual Studio Version should be greater than or equal to 12) and add an MVC Internet application,

I have given it a name "KnockoutWithMVC4".

Step3: You’ll get a full structured MVC application with default Home controller in the Controller folder. By default the entity framework is downloaded as a package inside application folder, but if not you can add entity framework package by right click the project, select manage nugget packages and search and install Entity Framework,

Generate the model from the data base, select your server and LearningKO database name, the connection string will automatically be added to your Web.Config, name that connection string as LearningKOEntities.

Select tables to be added to the model. In our case it’s Student Table.

Step5: Now add a new controller to the Controller folder, right click controller folder and add a controller named Student. Since we have already created our Datamodel, we can choose for an option where CRUD actions are created by chosen Entity Framework Datamodel,

Step8: Now press F5 to run the application, and you’ll see the list of all students we added in to table Student while creating it is displayed. Since the CRUD operations are automatically written, we have action results for display list and other Edit, Delete and Create operations. Note that views for all the operations are created in Views Folder under Student Folder name.

Now you can perform all the operations on this list.

Since I have not provided any validation checks on model or creating an existing student id, the code may break, so I am calling Edit Action in create when we find that id already exists,

Now create new student ,

We see that the student is created successfully and added to the list,

In data base,

Similarly for Edit,

Change any field and press save.The change will be reflected in the list and data base,

For Delete,

Student Deleted.

And in database,

So, that’s it, our first job is completed i.e. to create an MVC application, and perform CRUD operations using Entity Framework 5. You can see that until now we have not written a single line of code. Yes that’s the magic of MVC and EF. Cheers!

IX) Knockout Application

Our first job is well done,now moving on to our primary target, i.e. KO. Since KO depends largely on MVVM pattern, we’ll take MVVM at client side, and use our controller to be as same just modified little bit for returning JSON logic. You can learn about MVVM pattern and KO theory in first part of this article series.

Step1:

JQuery and Knockout.js files are very important to be in the solution’s script folder. Check to them and if you do not find them, then add the packages for jQuery and Knockout, in the same fashion as you added Entity Framework.Right click project, select "Manage nugget packages" and search for jQuery then install it , then search for knockout package and install it,

Step2: Right click Scripts folder and a folder named ViewModel.Add four js files to that folder, and name them as CreateVM.js, EditVM.js, DeleteVM.js and StudentListVM.js respectively. These are View Model files added to communicate to Controller and render our View templates.

On document load we apply bindings for CreateVM, then inside the view model method we initialize the observables to properties of Student, that will be bind to respective view.You can read more about observables in KO in first part of the series. There is a save function, that sends an ajax request to Student Controller’s Create method, and gets string result. data: ko.toJSON(this), means sending the object in JSON format to controller method.

Student/Create Controller Method

Modify the code of controller method of Create, to return JSON to the caller. The HTML templates bound with objects are actually bound to json properties, set in the methods of view model using Knockout Observables.

The work on observer pattern, so that when model is updated the views automatically gets updated and when views get updated the models update itself, this is called two way binding.

You can see I have used data-bind attribute of HTML5 to bind the View elements to View Models properties like data-bind="value: StudentId" , the same applies to all the editable elements. Click button is bound to SaveStudent method of view model.

At the end of the page we have registered the CreateVM.js view model for this particular view by

The return Json(db.Students.ToList(), JsonRequestBehavior.AllowGet); code returns the student object in json format, for binding to the view.

All set now, you can press F5 to run the application and we see, that application runs in the same manner as it executed before,

Now you can perform all the operations on this list.

Do not type anything else other than int for student id and Age, since validation checks are missing, they may cause error.

Now create new student ,

We see that the student is created successfully and added to the list,

In data base,

Similarly for Edit,

Change any field and press save.The change will be reflected in the list and data base,

For Delete,

Student Deleted.

And in database,

X) Knockout Attributes Glossary

. observable: Used to define model/entity properties. If these properties are bound with user interface and when value for these properties gets updated, automatically the UI elements bound with these properties will be updated with the new value instantaneously.

· observableArray: observableArray represents a collection of data elements which required notifications. It’s used to bind with the List kind of elements.

e.g this.Students = ko.observableArray([]);

· applyBindings: This is used to activate knockout for the current HTML document or a specific UI element in HTML document. The parameter for this method is the view-model which is defined in JavaScript. This ViewModel contains the observable, observableArray and various methods.

Various other types of binding are used in this article:

. click: Represents a click event handler added to the UI element so that JavaScript function is called.

. value: This represents the value binding with the UI element’s value property to the property defined into the ViewModel.

The value binding should be used with <input> , <select> , <textarea>

. visible: This is used to hide or unhide the UI element based upon the value passed to it’s binding.

. Text: This represent the text value of the parameter passed to the UI element.

XI) Conclusion

In this article of series Learning Knockout,we learned a lot of things about MVC, Entity Framework and Knockout.JS. We did practical hands on by creating a CRUD operations application too.

Excellent article! But I am having a little bit issue with showing Gender and domicile values in the dropdownlist. I followed all the instructions but these dropdown lists are not showing any values. Any help?

Sir I have created a mvc application using knockout to create an employee details(add) to the database using api controller. i have taken two js file i can add those data to the database by ajax post menthod but i would not get d data.i would like to get my data watever am going to add to the database and display in a new table in d same page wher am going to add my data.can u plz help me out how get the data using ajax
public class EmployeeController : ApiController
{
[HttpPost]
public IHttpActionResult CreateEmployee(Database.Employee employee)
{

Check the method name and parameters name you pass from your js files.These should be same as controller action name.And also check that have you rightly referenced your js file in the view or shared view.

Thanks
Do not forget to comment and rate the article if it helped you by any means.

same as wat the code in ur article was i have written the same but am getting an error at KOMVCModel.Context.cs

throw new UnintentionalCodeFirstException();
as

"An exception of type 'System.Data.Entity.Infrastructure.UnintentionalCodeFirstException' occurred in WebApplication9.dll but was not handled in user code

Additional information: The context is being used in Code First mode with code that was generated from an EDMX file for either Database First or Model First development. This will not work correctly. To fix this problem do not remove the line of code that throws this exception. If you wish to use Database First or Model First, then make sure that the Entity Framework connection string is included in the app.config or web.config of the start-up project. If you are creating your own DbConnection, then make sure that it is an EntityConnection and not some other type of DbConnection, and that you pass it to one of the base DbContext constructors that take a DbConnection. To learn more about Code First, Database First, and Model First see the Entity Framework documentation here: http://go.microsoft.com/fwlink/?LinkId=394715"

its geeting executed sir but while creating when am going to select gender i dont find options there its just showing empty and thank you so much sir for good article and quick response.
sir am using an api controller is the code same for an api controller whick is written in normal controller or there is any change to be done in it.

JQuery and Knockout.js files are very important to be in the solution’s script folder. Check to them and if you do not find them, then add the packages for jQuery and Knockout, in the same fashion as you added Entity Framework.Right click project, select "Manage nugget packages" and search for jQuery then install it , then search for knockout package and install it,

Follow step 1 of Section IX of the article.

Thanks
Do not forget to comment and rate the article if it helped you by any means.
For any technical requirement related to .net ,OOPS,C# and design patterns contact me on akhil.mittal20@gmail.com