Download Source Code Via Dropbox or Download Source Code Via Google Drive
I. Introduction
I have been browsing multiple sites for a complete end-to-end tutorial or article upon CRUD operations using Knockout.JS and MVC 4. Unfortunately all I found were incomplete or short explanations. In my last article we learned about imlementation of CRUD in ASP.Net web forms using MVC and EntityFramework. This article is the continuation of the series. My effort in this article will be a kind of tutorial to explain how to set up the knockout.js environment in a MVC4 application and perform CRUD operations on it.
2. Our Road-Map
We'll stick to our agenda of Learning Knockout.JS as follows:
3.> Part 2: Complete end-to-end CRUD operations using Knockout.JS and Entity Framework in MVC4 application
We'll continue to explain KO step-by-step in this article;the following are the toics:
- 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, yet without going very deep into theory, I would like to provide an introduction to MVC, Entity Framework and Knockout.
4. 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 specify 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 in a change in a Model's state.
To implement MVC in .NET we need mainly three classes (View, Controller and Model).
5. Entity Framework
Let's have a look at the 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 simple terms, 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 and storing the data in the database.
I hope this gives a glimpse of an ORM and EntityFramework.
6. Knockout.JS
Knockout.JS (KO) is basically a JS library that enables Declarative Bindings using an "Observable" View Model on the client (browser) following an observer pattern approach, enabling the 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 the MVVM pattern, in other words Model-View-View Model.
As the architecture is shown, Views interact with View Models in a two-way binding manner, in other words when the model is changed the view updates itself and when the view is updated, the model too updates itself instantaneously.
KO provides the following 3 most important features:
The entire idea of KO derives from these three major functionalities. KO also helps in developing Single Page Applications (SPAs). SPAs are an out-of-the box new way of developing Rich Internet Applications (RIAs) in today's era.
7. Application Architecture
The architecture is very much self-explanatory. The application works on a client-server model, where our MVC application or Web API application (not covered in this tutorial) will interact with an EntityFramework layer on the server side. The Entity Framework layer will be responsible for data transactions with the database.
On the client side we have HTML templates that will communicate with the server using Ajax calls and the templates will be bound to data via JSON objects through knockout observables (already explained in the first part).
8. MVC Application
Step 1: Create a database named LearningKO and add a table named student to it. The script of the table is as follows:
- USE [LearningKO]
- GO
- /****** Object: Table [dbo].[Student] Script Date: 12/04/2013 23:58:12 ******/
- SET ANSI_NULLS ON
- GO
- SET QUOTED_IDENTIFIER ON
- GO
- CREATE TABLE [dbo].[Student](
- [StudentId] [nvarchar](10) NOT NULL,
- [FirstName] [nvarchar](50) NULL,
- [LastName] [nvarchar](50) NULL,
- [Age] [int] NULL,
- [Gender] [nvarchar](50) NULL,
- [Batch] [nvarchar](50) NULL,
- [Address] [nvarchar](50) NULL,
- [Class] [nvarchar](50) NULL,
- [School] [nvarchar](50) NULL,
- [Domicile] [nvarchar](50) NULL,
- CONSTRAINT [PK_Student] PRIMARY KEY CLUSTERED
- (
- [StudentId] ASC
- )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,
- IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
- ) ON [PRIMARY]
- GO
- INSERT [dbo].[Student] ([StudentId], [FirstName], [LastName], [Age],
- [Gender], [Batch], [Address], [Class], [School], [Domicile]) VALUES (N'1',
- N'Akhil', N'Mittal', 28, N'Male', N'2006', N'Noida', N'Tenth', N'LFS',
- N'Delhi')
-
- INSERT [dbo].[Student] ([StudentId], [FirstName], [LastName], [Age],
- [Gender], [Batch], [Address], [Class], [School], [Domicile]) VALUES (N'2',
- N'Parveen', N'Arora', 25, N'Male', N'2007', N'Noida', N'8th', N'DPS',
- N'Delhi')
-
- INSERT [dbo].[Student] ([StudentId], [FirstName], [LastName], [Age],
- [Gender], [Batch], [Address], [Class], [School], [Domicile]) VALUES (N'3',
- N'Neeraj', N'Kumar', 38, N'Male', N'2011', N'Noida', N'10th', N'MIT',
- N'Outside Delhi')
-
- INSERT [dbo].[Student] ([StudentId], [FirstName], [LastName], [Age],
- [Gender], [Batch], [Address], [Class], [School], [Domicile]) VALUES (N'4',
- N'Ekta', N'Mittal', 25, N'Female', N'2005', N' Noida', N'12th', N'LFS',
- N'Delhi')
Step 2:Open your Visual Studio (the Visual Studio Version should be greater than or equal to 12 (Visual Studio 2013)) and add an MVC Internet application as in the following:
I have given it the name "KnockoutWithMVC4".
Step 3: Y>ou'll get a full structured MVC application with default Home controller in the Controller folder. By default Entity Framework is downloaded as a package inside the application folder; but if not then you can add an Entity Framework package by right-clicking the project, select "Manage Nugget packages" and search for and install Entity Framework as in the following:
Step 4: Right-click on the project file, select "Add new item" and add an ADO .Net Entity Data Model, then use the following procedure in the wizard:
Generate a model from the database, select your server and LearningKO database name. The connection string will automatically be added to your Web.Config, name that connection string "LearningKOEntities".
Select the tables to be added to the model. In our case it's Student Table.
Step 5: Now add a new controller to the Controller folder, right-click the 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 the chosen Entity Framework Datamodel as in the following:
- Name your controller "StudentController",
- From the Scaffolding Options, select "MVC controller with read/write actions and views, using Entity Framework".
- Select the Student Model class in the solution.
- Select Data context class as LearningKOEntities that was added to our solution when we added the EF data model.
- Select "Razor" as the rendering engine for views.
- Click the "Advanced" options, select "Layout or master page" and select "_Layout.cshtml" from the shared folder.
Step 6: We see our student controller prepared with all the CRUD operation actions as shown below:
- using System;
- using System.Collections.Generic;
- using System.Data;
- using System.Data.Entity;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- namespace KnockoutWithMVC4.Controllers
- {
- public class StudentController : Controller
- {
- private LearningKOEntities db = new LearningKOEntities();
-
-
- public ActionResult Index()
- {
- return View(db.Students.ToList());
- }
-
- public ActionResult Details(string id = null)
- {
- Student student = db.Students.Find(id);
- if (student == null)
- {
- return HttpNotFound();
- }
- return View(student);
- }
-
- public ActionResult Create()
- {
- return View();
- }
-
- [HttpPost]
- [ValidateAntiForgeryToken]
- public ActionResult Create(Student student)
- {
- if (ModelState.IsValid)
- {
- db.Students.Add(student);
- db.SaveChanges();
- return RedirectToAction("Index");
- }
- return View(student);
- }
-
- public ActionResult Edit(string id = null)
- {
- Student student = db.Students.Find(id);
- if (student == null)
- {
- return HttpNotFound();
- }
- return View(student);
- }
-
- [HttpPost]
- [ValidateAntiForgeryToken]
- public ActionResult Edit(Student student)
- {
- if (ModelState.IsValid)
- {
- db.Entry(student).State = EntityState.Modified;
- db.SaveChanges();
- return RedirectToAction("Index");
- }
- return View(student);
- }
-
- public ActionResult Delete(string id = null)
- {
- Student student = db.Students.Find(id);
- if (student == null)
- {
- return HttpNotFound();
- }
- return View(student);
- }
-
-
- [HttpPost, ActionName("Delete")]
- [ValidateAntiForgeryToken]
- public ActionResult DeleteConfirmed(string id)
- {
- Student student = db.Students.Find(id);
- db.Students.Remove(student);
- db.SaveChanges();
- return RedirectToAction("Index");
- }
- protected override void Dispose(bool disposing)
- {
- db.Dispose();
- base.Dispose(disposing);
- }
- }
- }
Step 7: Open the "App_Start" folder and change the name of the controller from "Home" to "Student", the code will as in the following:
- public static void RegisterRoutes(RouteCollection routes)
- {
- routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
- routes.MapRoute(
- name: "Default",
- url: "{controller}/{action}/{id}",
- defaults: new { controller = "Student", action = "Index", id = UrlParameter.Optional }
- );
- }
Step 8: Now press F5 to run the application. You'll see the list of all students we added to the table Student; while creating it, it is displayed. Since the CRUD operations are automatically written, we have action results for the display list and other Edit, Delete and Create operations.
Note that views for all the operations are created in the Views Folder under the Student Folder name.
Now you can perform all the operations on this list.
Since I have not provided any validation checks on the model or creating an existing student id, the code may break, so I am calling an Edit Action in the create when we find that the id already exists as in the following:
Now create new student as in the following:
We see that the student is created successfully and added to the list as in the following:
The database is as in the following:
Similarly an Edit is as in the following:
Change any field and press "Save". The change will be reflected in the list and database as in the following:
A Delete is as in the following:
Student Deleted.
And the database will be as in the following:
So, that's it, our first job is completed, in other words 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!
9. Knockout Application
Our first job is well done, now to proceed to our primary target, in other words KO. Since KO depends largely on the MVVM pattern, we'll use MVVM at the client side and use our controller to be the same but modified just a little bit for returning JSON logic. You can learn about the MVVM pattern and KO theory in the first part of this article series.
Step 1: The jQuery and Knockout.js files are very important to be in the solution's script folder. Look for 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 the project, select "Manage Nugget packages" and search for jQuery then install it , then search for the Knockout package and install it.
Step 2: Right-click the Scripts folder and on the folder named ViewModel. Add four JavaScript files to that folder, and name them as CreateVM.js, EditVM.js,DeleteVM.js and StudentListVM.js respectively.
These are View Model files added for communication with the Controller and ro render our View templates.
Step 3: Add some code to CreateVm.js as in the following:
- var urlPath = window.location.pathname;
- $(function () {
- ko.applyBindings(CreateVM);
- });
- var CreateVM = {
- Domiciles: ko.observableArray(['Delhi', 'Outside Delhi']),
- Genders: ko.observableArray(['Male', 'Female']),
- Students: ko.observableArray([]),
- StudentId: ko.observable(),
- FirstName: ko.observable(),
- LastName: ko.observable(),
- Age: ko.observable(),
- Batch: ko.observable(),
- Address: ko.observable(),
- Class: ko.observable(),
- School: ko.observable(),
- Domicile: ko.observable(),
- Gender: ko.observable(),
- SaveStudent: function () {
- $.ajax({
- url: '/Student/Create',
- type: 'post',
- dataType: 'json',
- data: ko.toJSON(this),
- contentType: 'application/json',
- success: function (result) {
- },
- error: function (err) {
- if (err.responseText == "Creation Failed")
- { window.location.href = '/Student/Index/'; }
- else {
- alert("Status:" + err.responseText);
- window.location.href = '/Student/Index/'; ;
- }
- },
- complete: function () {
- window.location.href = '/Student/Index/';
- }
- });
- }
- };
On document load we apply bindings for CreateVM, then inside the view model method we initialize the observables to the properties of the Student that will be bound to the respective view.You can read more about observables in KO in the first part of the series. There is a save function that sends an Ajax request to the Student Controller's Create method, and gets a string result. data: ko.toJSON(this), in other words sending the object in JSON format to the controller method.
Student/Create Controller Method
Modify the code of the 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 the view model using Knockout Observables.
The work is on the observer pattern, so that when the model is updated the views are automatically updated and when the views are updated the models update itself, this is called two-way binding.
Controller Code
- [HttpPost]
- public string Create(Student student)
- {
- if (ModelState.IsValid)
- {
- if (!StudentExists(student))
- db.Students.Add(student);
- else
- return Edit(student);
- db.SaveChanges();
- return "Student Created";
- }
- return "Creation Failed";
- }
View Code
Change the code of the views created previously to work with KO.
For "create.cshtml":
- <h2>
- Create</h2>
- <fieldset>
- <legend>Create Student</legend>
- <div class="editor-label">
- Student id
- </div>
- <div class="editor-field">
- <input data-bind="value: StudentId" />
- </div>
- <div class="editor-label">
- First Name
- </div>
- <div class="editor-field">
- <input data-bind="value: FirstName" />
- </div>
- <div class="editor-label">
- Last Name
- </div>
- <div class="editor-field">
- <input data-bind="value: LastName" />
- </div>
- <div class="editor-label">
- Age
- </div>
- <div class="editor-field">
- <input data-bind="value: Age" />
- </div>
- <div class="editor-label">
- Gender
- </div>
- <div class="editor-field">
- <select data-bind="options: Genders, value: Gender, optionsCaption: 'Select Gender...'">
- </select>
- </div>
- <div class="editor-label">
- Batch
- </div>
- <div class="editor-field">
- <input data-bind="value: Batch" />
- </div>
- <div class="editor-label">
- Address
- </div>
- <div class="editor-field">
- <input data-bind="value: Address" />
- </div>
- <div class="editor-label">
- Class
- </div>
- <div class="editor-field">
- <input data-bind="value: Class" />
- </div>
- <div class="editor-label">
- School
- </div>
- <div class="editor-field">
- <input data-bind="value: School" />
- </div>
- <div class="editor-label">
- Domicile
- </div>
- <div class="item ">
- <select data-bind="options: Domiciles, value: Domicile, optionsCaption: 'Select Domicile...'">
- </select>
- </div>
- <p>
- <button type="button" data-bind="click: SaveStudent">
- Save Student To Database</button>
- </p>
- </fieldset>
- <div>
- <a href="@Url.Action("Index", "Student")" >Back to List</a>
- </div>
- @section Scripts {
- @Scripts.Render("~/Scripts/ViewModels/CreateVM.js")
- }
You can see that I have used the data-bind attribute of HTML5 to bind the View elements to the View Models properties like data-bind="value: StudentId" , the same applies to all the editable elements. The Click button is bound to the SaveStudent method of the view model.
At the end of the page we have registered the CreateVM.js view model for this specific view by
- @section Scripts {
- @Scripts.Render("~/Scripts/ViewModels/CreateVM.js")
- }
>Tag.
Step 3: We do the same set of operations for all the views, View models and the Controller method, the code is as below.
For Edit
View Model
Code is to be added in StudentListVM for Edit View Model, since it only performs a get when it loads.
Controller methods
- public ActionResult Edit(string id=null)
- {
- Student student = db.Students.Find(id);
- if (student == null)
- {
- return null;
- }
- JavaScriptSerializer serializer = new JavaScriptSerializer();
- ViewBag.InitialData = serializer.Serialize(student);
- return View();
- }
-
-
-
-
-
- [HttpPost]
- public string Edit(Student student)
- {
- if (ModelState.IsValid)
- {
- db.Entry(student).State = EntityState.Modified;
- db.SaveChanges();
- return "Student Edited";
- }
- return "Edit Failed";
- }
View
- <h2>
- Edit</h2>
- <fieldset>
- <legend>Edit Student</legend>
- <div class="editor-label">
- Student id
- </div>
- <div class="editor-field">
- <input data-bind="value: StudentId" readonly="readonly" />
- </div>
- <div class="editor-label">
- First Name
- </div>
- <div class="editor-field">
- <input data-bind="value: FirstName" />
- </div>
- <div class="editor-label">
- Last Name
- </div>
- <div class="editor-field">
- <input data-bind="value: LastName" />
- </div>
- <div class="editor-label">
- Age
- </div>
- <div class="editor-field">
- <input data-bind="value: Age" />
- </div>
- <div class="editor-label">
- Gender
- </div>
- <div class="editor-field">
- <select data-bind="options: Genders, value: Gender, optionsCaption: 'Select Gender...'">
- </select>
- </div>
- <div class="editor-label">
- Batch
- </div>
- <div class="editor-field">
- <input data-bind="value: Batch" />
- </div>
- <div class="editor-label">
- Address
- </div>
- <div class="editor-field">
- <input data-bind="value: Address" />
- </div>
- <div class="editor-label">
- Class
- </div>
- <div class="editor-field">
- <input data-bind="value: Class" />
- </div>
- <div class="editor-label">
- School
- </div>
- <div class="editor-field">
- <input data-bind="value: School" />
- </div>
- <div class="editor-label">
- Domicile
- </div>
- <div class="editor-field">
- <select data-bind="options: Domiciles, value: Domicile, optionsCaption: 'Select Domicile...'">
- </select>
- </div>
- <p>
- <button type="button" data-bind="click: SaveStudent">
- Save Student To Database</button>
- </p>
- </fieldset>
- <div>
- <a href="@Url.Action("Index", "Student")">Back to List</a>
- </div>
- @section Scripts {
- <script>
- $(function () {
- ko.applyBindings(EditVM);
- });
- var initialData = '@Html.Raw(ViewBag.InitialData)';
- var parsedJSON = $.parseJSON(initialData);
- var EditVM = {
- Domiciles: ko.observableArray(['Delhi', 'Outside Delhi']),
- Genders: ko.observableArray(['Male', 'Female']),
- Students: ko.observableArray([]),
- StudentId: ko.observable(parsedJSON.StudentId),
- FirstName: ko.observable(parsedJSON.FirstName),
- LastName: ko.observable(parsedJSON.LastName),
- Age: ko.observable(parsedJSON.Age),
- Batch: ko.observable(parsedJSON.Batch),
- Address: ko.observable(parsedJSON.Address),
- Class: ko.observable(parsedJSON.Class),
- School: ko.observable(parsedJSON.School),
- Domicile: ko.observable(parsedJSON.Domicile),
- Gender: ko.observable(parsedJSON.Gender),
- SaveStudent: function () {
- $.ajax({
- url: '/Student/Edit',
- type: 'post',
- dataType: 'json',
- data: ko.toJSON(this),
- contentType: 'application/json',
- success: function (result) {
- },
- error: function (err) {
- if (err.responseText == "Creation Failed")
- { window.location.href = '/Student/Index/'; }
- else {
- alert("Status:" + err.responseText);
- window.location.href = '/Student/Index/'; ;
- }
- },
- complete: function () {
- window.location.href = '/Student/Index/';
- }
- });
- }
- };
- </script>
- }
>
For Delete
View Model
Code is to be added in StudentListVM for the Edit View Model, since it only performs a get when it loads.
Controller methods
- public ActionResult Delete(string id = null)
- {
- Student student = db.Students.Find(id);
- if (student == null)
- {
- return null;
- }
- JavaScriptSerializer serializer = new JavaScriptSerializer();
- ViewBag.InitialData = serializer.Serialize(student);
- return View();
- }
-
-
-
-
-
- [HttpPost]
- public string Delete(Student student)
- {
- Student studentDetail = db.Students.Find(student.StudentId);
- db.Students.Remove(studentDetail);
- db.SaveChanges();
- return "Student Deleted";
- }
View
- @model KnockoutWithMVC4.Student
- @{
- ViewBag.Title = "Delete";
- }
- <h2>
- Delete Student</h2>
- <h3>
- Are you sure you want to delete this?</h3>
- <fieldset>
- <legend>Delete</legend>
- <div class="display-label">
- Student Id
- </div>
- <div class="display-field">
- <input data-bind="value: StudentId" />
- </div>
- <div class="display-label">
- First Name
- </div>
- <div class="display-field">
- <input data-bind="value: FirstName" />
- </div>
- <div class="display-label">
- Last Name
- </div>
- <div class="display-field">
- <input data-bind="value: LastName" />
- </div>
- <div class="display-label">
- Age
- </div>
- <div class="display-field">
- <input data-bind="value: Age" />
- </div>
- <div class="display-label">
- Gender
- </div>
- <div class="display-field">
- <input data-bind="value: Gender" />
- </div>
- <div class="display-label">
- Batch
- </div>
- <div class="display-field">
- <input data-bind="value: Batch" />
- </div>
- <div class="display-label">
- Address
- </div>
- <div class="display-field">
- <input data-bind="value: Address" />
- </div>
- <div class="display-label">
- Class
- </div>
- <div class="display-field">
- <input data-bind="value: Class" />
- </div>
- <div class="display-label">
- School
- </div>
- <div class="display-field">
- <input data-bind="value: School" />
- </div>
- <div class="display-label">
- Domicile
- </div>
- <div class="display-field">
- <input data-bind="value: Domicile" />
- </div>
- </fieldset>
- <p>
- <button type="button" data-bind="click: DeleteStudent">Delete Student</button> |
- <a href="@Url.Action("Index", "Student")">Back to List</a>
- </p>
- @section Scripts {
- <script>
- $(function () {
- ko.applyBindings(DeleteVM);
- });
- var initialData = '@Html.Raw(ViewBag.InitialData)';
- var parsedJSON = $.parseJSON(initialData);
- var DeleteVM = {
- Domiciles: ko.observableArray(['Delhi', 'Outside Delhi']),
- Genders: ko.observableArray(['Male', 'Female']),
- Students: ko.observableArray([]),
- StudentId: ko.observable(parsedJSON.StudentId),
- FirstName: ko.observable(parsedJSON.FirstName),
- LastName: ko.observable(parsedJSON.LastName),
- Age: ko.observable(parsedJSON.Age),
- Batch: ko.observable(parsedJSON.Batch),
- Address: ko.observable(parsedJSON.Address),
- Class: ko.observable(parsedJSON.Class),
- School: ko.observable(parsedJSON.School),
- Domicile: ko.observable(parsedJSON.Domicile),
- Gender: ko.observable(parsedJSON.Gender),
- DeleteStudent: function () {
- $.ajax({
- url: '/Student/Delete',
- type: 'post',
- dataType: 'json',
- data: ko.toJSON(this),
- contentType: 'application/json',
- success: function (result) {
- },
- error: function (err) {
- if (err.responseText == "Creation Failed")
- { window.location.href = '/Student/Index/'; }
- else {
- alert("Status:" + err.responseText);
- window.location.href = '/Student/Index/'; ;
- }
- },
- complete: function () {
- window.location.href = '/Student/Index/';
- }
- });
- }
- };
- </script>
- }
For Index (to the display list)
View Model
- var urlPath = window.location.pathname;
- $(function () {
- ko.applyBindings(StudentListVM);
- StudentListVM.getStudents();
- });
-
- var StudentListVM = {
- Students: ko.observableArray([]),
- getStudents: function () {
- var self = this;
- $.ajax({
- type: "GET",
- url: '/Student/FetchStudents',
- contentType: "application/json; charset=utf-8",
- dataType: "json",
- success: function (data) {
- self.Students(data);
- },
- error: function (err) {
- alert(err.status + " : " + err.statusText);
- }
- });
- },
- };
- self.editStudent = function (student) {
- window.location.href = '/Student/Edit/' + student.StudentId;
- };
- self.deleteStudent = function (student) {
- window.location.href = '/Student/Delete/' + student.StudentId;
- };
-
- function Students(data) {
- this.StudentId = ko.observable(data.StudentId);
- this.FirstName = ko.observable(data.FirstName);
- this.LastName = ko.observable(data.LastName);
- this.Age = ko.observable(data.Age);
- this.Gender = ko.observable(data.Gender);
- this.Batch = ko.observable(data.Batch);
- this.Address = ko.observable(data.Address);
- this.Class = ko.observable(data.Class);
- this.School = ko.observable(data.School);
- this.Domicile = ko.observable(data.Domicile);
- }
Controller methods
- public JsonResult FetchStudents()
- {
- return Json(db.Students.ToList(), JsonRequestBehavior.AllowGet);
- }
View
- @model IEnumerable<KnockoutWithMVC4.Student>
- @{
- ViewBag.Title = "Index";
- }
- <h2>Students List</h2>
- <p><a href="@Url.Action("Create", "Student")" >Create Student</a></p>
- <table>
- <thead>
- <tr>
- <th>Student Id</th>
- <th>First Name</th>
- <th>Last Name</th>
- <th>Age</th>
- <th>Gender</th>
- <th>Batch</th>
- <th>Address</th>
- <th>Class</th>
- <th>School</th>
- <th>Domicile</th>
- <th></th>
- </tr>
- </thead>kk
- <tbody data-bind="foreach: Students">
- <tr>
- <td data-bind="text: StudentId"></td>
- <td data-bind="text: FirstName"></td>
- <td data-bind="text: LastName"></td>
- <td data-bind="text: Age"></td>
- <td data-bind="text: Gender"></td>
- <td data-bind="text: Batch"></td>
- <td data-bind="text: Address"></td>
- <td data-bind="text: Class"></td>
- <td data-bind="text: School"></td>
- <td data-bind="text: Domicile"></td>
- <td>
- <a data-bind="click: editStudent">Edit</a>
- <a data-bind="click: deleteStudent">Delete</a>
- </td>
- </tr>
- </tbody>
- </table>
- @section Scripts {
- @Scripts.Render("~/Scripts/ViewModels/StudentListVM.js")
- }
>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 the 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 the validation checks are missing, they may cause an error.
Now create a new student >as in the following:
We see that the student is created successfully and added to the list as in the following:
In the database:
Similarly for Edit:
Change any field and press "Save". The change will be reflected in the list and the database.
For Delete:
The Student has been deleted.
And in the database:
10. Knockout Attributes Glossary
-
.observable: Used to define model/entity properties. If these properties are bound with the user interface and when the value for these properties are updated,
the UI elements automatically bound with these properties will be updated with the new value instantaneously.
For example this.StudentId = ko.observable("1"); - => StudentId is the observable property. KO represents an object for the Knockout.js library.
The value of the observable is read as var id= this. StudentId ();
-
.observableArray: observableArray represents a collection of data elements that require 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 the HTML document. The parameter for this method
is the view-model that 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 the JavaScript function is called.
-
.value: This represents the value binding with the UI element's value property to the property defined in the ViewModel.
The value binding should be used with <input>, <select> and <textarea>.
-
.visible: This is used to hide or unhide the UI element based upon the value ed to it's binding.
-
.Text: This represent the text value of the parameter ed to the UI element.
11. Conclusion
In this article of series about Knockout, we learned many things about MVC, Entity Framework and Knockout.JS. We did practical hands-on exercises by creating a CRUD operations application too.
Therefore we can mark it as tasks done. We'll be covering more topics in my future articles.
Note: A few of the images in this article are taken via Google search. You can follow my articles at: codeteddy.com