In this post, we are going to create an 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. Now, let’s begin.

Download source code

Introduction about Knockout JS

According to Knockout JS documentation, Knockout is a JavaScript library that helps you to create rich and responsive display and editor UI with a clean underlying data model. Any time, you have sections of UI that updates dynamically (e.g., changing depending on the user’s actions or when an external data source changes), KO can help you to implement it more simply and maintainable.

It has benefits, as shown below.

  • Pure JavaScript library works with any Server or client-side technology.
    Can be added on top of your existing Web Application without requiring major architectural changes.
  • Compact - around 13kb after gzipping
    Works on any mainstream Browser (IE 6+, Firefox 2+, Chrome, Safari, Edge, others).
  • Comprehensive suite of specifications (developed BDD-style) means its correct functioning can easily be verified on the new Browsers and platforms.
Background

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 an MVC CRUD application with the help of Knockout JS. I hope, you will like this.

Create an Empty MVC Application

To get started, we will create an empty MVC application, as shown below.


add_new_empty_mvc_project

Creating database and Entity Data Model

Here, I am creating a database with the name “TrialDB”. You can always create a DB by running the query given below.
  1. USE [master]
  2. GO
  3. /****** Object: Database [TrialDB] Script Date: 20-11-2016 03:54:53 PM ******/
  4. CREATE DATABASE [TrialDB]
  5. CONTAINMENT = NONE
  6. ON PRIMARY
  7. ( NAME = N'TrialDB', FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL13.SQLEXPRESS\MSSQL\DATA\TrialDB.mdf' , SIZE = 8192KB , MAXSIZE = UNLIMITED, FILEGROWTH = 65536KB )
  8. LOG ON
  9. ( NAME = N'TrialDB_log', FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL13.SQLEXPRESS\MSSQL\DATA\TrialDB_log.ldf' , SIZE = 8192KB , MAXSIZE = 2048GB , FILEGROWTH = 65536KB )
  10. GO
  11. ALTER DATABASE [TrialDB] SET COMPATIBILITY_LEVEL = 130
  12. GO
  13. IF (1 = FULLTEXTSERVICEPROPERTY('IsFullTextInstalled'))
  14. begin
  15. EXEC [TrialDB].[dbo].[sp_fulltext_database] @action = 'enable'
  16. end
  17. GO
  18. ALTER DATABASE [TrialDB] SET ANSI_NULL_DEFAULT OFF
  19. GO
  20. ALTER DATABASE [TrialDB] SET ANSI_NULLS OFF
  21. GO
  22. ALTER DATABASE [TrialDB] SET ANSI_PADDING OFF
  23. GO
  24. ALTER DATABASE [TrialDB] SET ANSI_WARNINGS OFF
  25. GO
  26. ALTER DATABASE [TrialDB] SET ARITHABORT OFF
  27. GO
  28. ALTER DATABASE [TrialDB] SET AUTO_CLOSE OFF
  29. GO
  30. ALTER DATABASE [TrialDB] SET AUTO_SHRINK OFF
  31. GO
  32. ALTER DATABASE [TrialDB] SET AUTO_UPDATE_STATISTICS ON
  33. GO
  34. ALTER DATABASE [TrialDB] SET CURSOR_CLOSE_ON_COMMIT OFF
  35. GO
  36. ALTER DATABASE [TrialDB] SET CURSOR_DEFAULT GLOBAL
  37. GO
  38. ALTER DATABASE [TrialDB] SET CONCAT_NULL_YIELDS_NULL OFF
  39. GO
  40. ALTER DATABASE [TrialDB] SET NUMERIC_ROUNDABORT OFF
  41. GO
  42. ALTER DATABASE [TrialDB] SET QUOTED_IDENTIFIER OFF
  43. GO
  44. ALTER DATABASE [TrialDB] SET RECURSIVE_TRIGGERS OFF
  45. GO
  46. ALTER DATABASE [TrialDB] SET DISABLE_BROKER
  47. GO
  48. ALTER DATABASE [TrialDB] SET AUTO_UPDATE_STATISTICS_ASYNC OFF
  49. GO
  50. ALTER DATABASE [TrialDB] SET DATE_CORRELATION_OPTIMIZATION OFF
  51. GO
  52. ALTER DATABASE [TrialDB] SET TRUSTWORTHY OFF
  53. GO
  54. ALTER DATABASE [TrialDB] SET ALLOW_SNAPSHOT_ISOLATION OFF
  55. GO
  56. ALTER DATABASE [TrialDB] SET PARAMETERIZATION SIMPLE
  57. GO
  58. ALTER DATABASE [TrialDB] SET READ_COMMITTED_SNAPSHOT OFF
  59. GO
  60. ALTER DATABASE [TrialDB] SET HONOR_BROKER_PRIORITY OFF
  61. GO
  62. ALTER DATABASE [TrialDB] SET RECOVERY SIMPLE
  63. GO
  64. ALTER DATABASE [TrialDB] SET MULTI_USER
  65. GO
  66. ALTER DATABASE [TrialDB] SET PAGE_VERIFY CHECKSUM
  67. GO
  68. ALTER DATABASE [TrialDB] SET DB_CHAINING OFF
  69. GO
  70. ALTER DATABASE [TrialDB] SET FILESTREAM( NON_TRANSACTED_ACCESS = OFF )
  71. GO
  72. ALTER DATABASE [TrialDB] SET TARGET_RECOVERY_TIME = 60 SECONDS
  73. GO
  74. ALTER DATABASE [TrialDB] SET DELAYED_DURABILITY = DISABLED
  75. GO
  76. ALTER DATABASE [TrialDB] SET QUERY_STORE = OFF
  77. GO
  78. USE [TrialDB]
  79. GO
  80. ALTER DATABASE SCOPED CONFIGURATION SET MAXDOP = 0;
  81. GO
  82. ALTER DATABASE SCOPED CONFIGURATION FOR SECONDARY SET MAXDOP = PRIMARY;
  83. GO
  84. ALTER DATABASE SCOPED CONFIGURATION SET LEGACY_CARDINALITY_ESTIMATION = OFF;
  85. GO
  86. ALTER DATABASE SCOPED CONFIGURATION FOR SECONDARY SET LEGACY_CARDINALITY_ESTIMATION = PRIMARY;
  87. GO
  88. ALTER DATABASE SCOPED CONFIGURATION SET PARAMETER_SNIFFING = ON;
  89. GO
  90. ALTER DATABASE SCOPED CONFIGURATION FOR SECONDARY SET PARAMETER_SNIFFING = PRIMARY;
  91. GO
  92. ALTER DATABASE SCOPED CONFIGURATION SET QUERY_OPTIMIZER_HOTFIXES = OFF;
  93. GO
  94. ALTER DATABASE SCOPED CONFIGURATION FOR SECONDARY SET QUERY_OPTIMIZER_HOTFIXES =PRIMARY;
  95. GO
  96. ALTER DATABASE [TrialDB] SET READ_WRITE
  97. GO
Create a table

To create a table, you can run the query given below.
  1. USE [TrialDB]
  2. GO
  3. /****** Object: Table [dbo].[Course] Script Date: 20-11-2016 03:57:30 PM ******/
  4. SET ANSI_NULLS ON
  5. GO
  6. SET QUOTED_IDENTIFIER ON
  7. GO
  8. CREATE TABLE [dbo].[Course](
  9. [CourseID] [int] NOT NULL,
  10. [CourseName] [nvarchar](50) NOT NULL,
  11. [CourseDescription] [nvarchar](100) NULL,
  12. CONSTRAINT [PK_Course] PRIMARY KEY CLUSTERED
  13. (
  14. [CourseID] ASC
  15. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
  16. ) ON [PRIMARY]
  17. GO
Thus, our database is ready. Now, we will create an Entity Data Model with the database, which we created.


create_entity_data_model

Install Knockout JS

To install Knockout JS in your project, please right click on your project, click on Manage NuGet Package, and search for ‘Knockout’.


install_knockout

Now, let us start our coding as everything is set.

C – Create Operation

Thus, 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 to create operation.
  1. // GET: Home/Create
  2. public ActionResult Create() {
  3. return View();
  4. }
  5. // POST: Home/Create
  6. [HttpPost]
  7. public string Create(Course course) {
  8. if (!ModelState.IsValid) return "Model is invalid";
  9. _db.Courses.Add(course);
  10. _db.SaveChanges();
  11. return "Cource is created";
  12. } // This is just a sample script. Paste your real code (javascript or HTML) here.
  13. if ('this_is' == /an_example/) {
  14. of_beautifier();
  15. } else {
  16. var a = b ? (c % d) : e[f];
  17. }
Here, the first action calls the View for the create operation and the second operation is used to insert the data to the database and _db is our entity.

private readonly TrialDBEntities _db = new TrialDBEntities();

Now, let’s go ahead and create View to create operation.
  1. @model MVCCRUDKnockout.Models.Course
  2. @ {
  3. ViewBag.Title = "Create";
  4. } <
  5. div class = "form-horizontal" >
  6. <
  7. h4 > Course < /h4> <
  8. hr >
  9. <
  10. div class = "form-group" >
  11. <
  12. label class = "control-label col-md-2"
  13. for = "CourseName" > CourseName < /label> <
  14. div class = "col-md-10" >
  15. <
  16. input class = "form-control text-box single-line"
  17. id = "CourseName"
  18. name = "CourseName"
  19. type = "text"
  20. value = ""
  21. data - bind = "value: CourseName" >
  22. <
  23. /div> <
  24. /div> <
  25. div class = "form-group" >
  26. <
  27. label class = "control-label col-md-2"
  28. for = "CourseDescription" > CourseDescription < /label> <
  29. div class = "col-md-10" >
  30. <
  31. input class = "form-control text-box single-line"
  32. id = "CourseDescription"
  33. name = "CourseDescription"
  34. type = "text"
  35. value = ""
  36. data - bind = "value: CourseDescription" >
  37. <
  38. /div> <
  39. /div> <
  40. div class = "form-group" >
  41. <
  42. div class = "col-md-offset-2 col-md-10" >
  43. <
  44. input type = "button"
  45. data - bind = "click: createCourse"
  46. value = "Create"
  47. class = "btn btn-default" >
  48. <
  49. /div> <
  50. /div> <
  51. /div> <
  52. div >
  53. @Html.ActionLink("Back to List", "Read") <
  54. /div> <
  55. script src = "~/Scripts/jquery-1.10.2.min.js" > < /script> <
  56. script src = "~/Scripts/knockout-3.4.0.js" > < /script> <
  57. script src = "~/Scripts/KOScripts/KOCreate.js" > < /script>
Did you notice that we are binding the data to our input controls as data-bind=”value: CourseName”? This value is related to the view model, which we are going to set. The interesting this is, the values in the model will be changed as you change the values in the input. You don’t need to add any kind of codes for the operations.

At last, we are binding a click event, as shown below.
  1. <input type="button" data-bind="click: createCourse" value="Create" class="btn btn-default">
This will call the function createCourse, 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 Knockout JS documentation.

MVVM and View Models

Model-View-View Model (MVVM) is a design pattern to build the user interfaces. It describes how you can keep a potentially sophisticated UI simple by splitting it into the three parts.

When using KO, your view is simply your HTML document with the declarative bindings to link it to the view model. Alternatively, you can use the templates that generates HTML, using data from your view model.

Now, going back to our create operation, KOCreate.js is the file, where we are going to write our operation. Now, please open the file and bind view model, as shown below.

  1. $(function () {
  2. ko.applyBindings(modelCreate);
  3. });

knockout_apply_bindings

Now, preceding is our view model and the associated functions.
  1. var modelCreate = {
  2. CourseName: ko.observable(),
  3. CourseDescription: ko.observable(),
  4. createCourse: function() {
  5. try {
  6. $.ajax({
  7. url: '/Home/Create',
  8. type: 'post',
  9. dataType: 'json',
  10. data: ko.toJSON(this), //Here the data wil be converted to JSON
  11. contentType: 'application/json',
  12. success: successCallback,
  13. error: errorCallback
  14. });
  15. } catch (e) {
  16. window.location.href = '/Home/Read/';
  17. }
  18. }
  19. };
  20. function successCallback(data) {
  21. window.location.href = '/Home/Read/';
  22. }
  23. function errorCallback(err) {
  24. window.location.href = '/Home/Read/';
  25. }
Here, ko.observable() are the special objects, which can notify the changes and update the model accordingly. Thus, if you need to update your UI automatically, when the view model changes, you can use observable().Now, please run your view and check whether it is working fine.


create_page

R – Read operation

As we have completed our create operation, now it is the time for Read. Please open your controller and write the actions, as shown below.
  1. // GET: Home
  2. public ActionResult Read() {
  3. return View();
  4. }
  5. //GET All Courses
  6. public JsonResult ListCourses() {
  7. return Json(_db.Courses.ToList(), JsonRequestBehavior.AllowGet);
  8. }
You can create your Read view as preceding.
  1. @{
  2. ViewBag.Title = "Read";
  3. }
  4. <h2>Index</h2>
  5. <p>
  6. @Html.ActionLink("Create New", "Create")
  7. </p>
  8. <table class="table">
  9. <tr>
  10. <th>
  11. Course Name
  12. </th>
  13. <th>
  14. Course Description
  15. </th>
  16. <th></th>
  17. </tr>
  18. <tbody data-bind="foreach: Courses">
  19. <tr>
  20. <td data-bind="text: CourseName"></td>
  21. <td data-bind="text: CourseDescription"></td>
  22. <td>
  23. <a data-bind="attr: { 'href': '@Url.Action("Edit", "Home")/' + CourseID }"class="btn-link">Edit</a>
  24. <a data-bind="attr: { 'href': '@Url.Action("Delete", "Home")/' + CourseID }"class="btn-link">Delete</a>
  25. </td>
  26. </tr>
  27. </tbody>
  28. </table>
  29. <script src="~/Scripts/jquery-1.10.2.min.js"></script>
  30. <script src="~/Scripts/knockout-3.4.0.js"></script>
  31. <script src="~/Scripts/KOScripts/KORead.js"></script>
Here, we are using data-bind=”foreach: Courses” for looping through our model, which we are going to create now. Thus, shall we do it? Please create a JS file with the name KORead.js and add the code, mentioned below.
  1. $(function() {
  2. ko.applyBindings(modelView);
  3. modelView.viewCourses();
  4. });
  5. var modelView = {
  6. Courses: ko.observableArray([]),
  7. viewCourses: function() {
  8. var thisObj = this;
  9. try {
  10. $.ajax({
  11. url: '/Home/ListCourses',
  12. type: 'GET',
  13. dataType: 'json',
  14. contentType: 'application/json',
  15. success: function(data) {
  16. thisObj.Courses(data); //Here we are assigning values to KO Observable array
  17. },
  18. error: function(err) {
  19. alert(err.status + " : " + err.statusText);
  20. }
  21. });
  22. } catch (e) {
  23. window.location.href = '/Home/Read/';
  24. }
  25. }
  26. };
Here, goes the output.


read_page

Now, it is the time for update operation. Are you ready?

U – Update operation

As we did for the two operations, mentioned above, let us create some actions in our controller first.
  1. // GET: Home/Edit/5
  2. public ActionResult Edit(int ? id) {
  3. if (id == null)
  4. return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
  5. var course = _db.Courses.Find(id);
  6. if (course == null)
  7. return HttpNotFound();
  8. var serializer = new JavaScriptSerializer();
  9. ViewBag.SelectedCourse = serializer.Serialize(course);
  10. return View();
  11. }
  12. // POST: Home/Update/5
  13. [HttpPost]
  14. public string Update(Course course) {
  15. if (!ModelState.IsValid) return "Invalid model";
  16. _db.Entry(course).State = EntityState.Modified;
  17. _db.SaveChanges();
  18. return "Updated successfully";
  19. }
Here, the first action with the parameter ID is called, whenever a user clicks on Edit link from the table we created. We are setting the queried data to ViewBag, so that we can use it for our related operation. For now, we can create a view, as shown below.
  1. @ {
  2. ViewBag.Title = "Edit";
  3. } <
  4. h2 > Edit < /h2>
  5. @using(Html.BeginForm()) {
  6. @Html.AntiForgeryToken() <
  7. div class = "form-horizontal" >
  8. <
  9. h4 > Course < /h4> <
  10. div class = "form-group" >
  11. <
  12. label class = "control-label col-md-2"
  13. for = "CourseName" > CourseName < /label> <
  14. div class = "col-md-10" >
  15. <
  16. input class = "form-control text-box single-line"
  17. id = "CourseName"
  18. name = "CourseName"
  19. type = "text"
  20. value = ""
  21. data - bind = "value: CourseName" >
  22. <
  23. /div> <
  24. /div> <
  25. div class = "form-group" >
  26. <
  27. label class = "control-label col-md-2"
  28. for = "CourseDescription" > CourseDescription < /label> <
  29. div class = "col-md-10" >
  30. <
  31. input class = "form-control text-box single-line"
  32. id = "CourseDescription"
  33. name = "CourseDescription"
  34. type = "text"
  35. value = ""
  36. data - bind = "value: CourseDescription" >
  37. <
  38. /div> <
  39. /div> <
  40. div class = "form-group" >
  41. <
  42. div class = "col-md-offset-2 col-md-10" >
  43. <
  44. input type = "button"
  45. data - bind = "click: updateCourse"
  46. value = "Update"
  47. class = "btn btn-default" >
  48. <
  49. /div> <
  50. /div> <
  51. /div>
  52. } <
  53. script type = "text/javascript" >
  54. var selectedCourse = '@Html.Raw(ViewBag.selectedCourse)'; <
  55. /script> <
  56. div >
  57. @Html.ActionLink("Back to List", "Read") <
  58. /div> < script src = "~/Scripts/jquery-1.10.2.min.js" > < /script>
  59. <script src = "~/Scripts/knockout-3.4.0.js" > < /script>
  60. < script src = "~/Scripts/KOScripts/KOUpdate.js" > < /script>
Create a JS with the name KOUpdate.js and add the code, mentioned below
  1. var parsedSelectedCourse = $.parseJSON(selectedCourse);
  2. $(function() {
  3. ko.applyBindings(modelUpdate);
  4. });
  5. var modelUpdate = {
  6. CourseID: ko.observable(parsedSelectedCourse.CourseID),
  7. CourseName: ko.observable(parsedSelectedCourse.CourseName),
  8. CourseDescription: ko.observable(parsedSelectedCourse.CourseDescription),
  9. updateCourse: function() {
  10. try {
  11. $.ajax({
  12. url: '/Home/Update',
  13. type: 'POST',
  14. dataType: 'json',
  15. data: ko.toJSON(this),
  16. contentType: 'application/json',
  17. success: successCallback,
  18. error: errorCallback
  19. });
  20. } catch (e) {
  21. window.location.href = '/Home/Read/';
  22. }
  23. }
  24. };
  25. function successCallback(data) {
  26. window.location.href = '/Home/Read/';
  27. }
  28. function errorCallback(err) {
  29. window.location.href = '/Home/Read/';
  30. }
Now, run your application and see the Edit/Update operation.


edit_page

D – Delete operation

So our last operation, Delete. Let’s edit our controller as follows.
  1. // GET: Home/Delete/5
  2. public ActionResult Delete(int ? id) {
  3. if (id == null)
  4. return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
  5. var course = _db.Courses.Find(id);
  6. if (course == null)
  7. return HttpNotFound();
  8. var serializer = new JavaScriptSerializer();
  9. ViewBag.SelectedCourse = serializer.Serialize(course);
  10. return View();
  11. }
  12. // POST: Home/Delete/5
  13. [HttpPost, ActionName("Delete")]
  14. public string Delete(Course course) {
  15. if (course == null) return "Invalid data";
  16. var getCourse = _db.Courses.Find(course.CourseID);
  17. _db.Courses.Remove(getCourse);
  18. _db.SaveChanges();
  19. return "Deleted successfully";
  20. }
The code looks exactly same as our update operation, so there is no explanation. Still if you get any issues, please ask. Now, let us create our view.
  1. @model MVCCRUDKnockout.Models.Course
  2. @ {
  3. ViewBag.Title = "Delete";
  4. } <
  5. h2 > Delete < /h2> <
  6. h3 > Are you sure you want to delete this ? < /h3>
  7. @using(Html.BeginForm()) {
  8. @Html.AntiForgeryToken() <
  9. div class = "form-horizontal" >
  10. <
  11. h4 > Course < /h4> <
  12. div class = "form-group" >
  13. <
  14. label class = "control-label col-md-2"
  15. for = "CourseName" > CourseName < /label> <
  16. div class = "col-md-10" >
  17. <
  18. input class = "form-control text-box single-line"
  19. id = "CourseName"
  20. name = "CourseName"
  21. type = "text"
  22. value = ""
  23. data - bind = "value: CourseName" >
  24. <
  25. /div> <
  26. /div> <
  27. div class = "form-group" >
  28. <
  29. label class = "control-label col-md-2"
  30. for = "CourseDescription" > CourseDescription < /label> <
  31. div class = "col-md-10" >
  32. <
  33. input class = "form-control text-box single-line"
  34. id = "CourseDescription"
  35. name = "CourseDescription"
  36. type = "text"
  37. value = ""
  38. data - bind = "value: CourseDescription" >
  39. <
  40. /div> <
  41. /div> <
  42. div class = "form-group" >
  43. <
  44. div class = "col-md-offset-2 col-md-10" >
  45. <
  46. input type = "button"
  47. data - bind = "click: deleteCourse"
  48. value = "Delete"
  49. class = "btn btn-default" >
  50. <
  51. /div> <
  52. /div> <
  53. /div>
  54. } <
  55. script type = "text/javascript" >
  56. var selectedCourse = '@Html.Raw(ViewBag.selectedCourse)'; <
  57. /script> <
  58. div >
  59. @Html.ActionLink("Back to List", "Read") <
  60. /div> <
  61. script src = "~/Scripts/jquery-1.10.2.min.js" > < /script> <
  62. script src = "~/Scripts/knockout-3.4.0.js" > < /script> <
  63. script src = "~/Scripts/KOScripts/KODelete.js" > < /script>
You can always create our knockout codes, as shown.
  1. var parsedSelectedCourse = $.parseJSON(selectedCourse);
  2. $(function() {
  3. ko.applyBindings(modelDelete);
  4. });
  5. var modelDelete = {
  6. CourseID: ko.observable(parsedSelectedCourse.CourseID),
  7. CourseName: ko.observable(parsedSelectedCourse.CourseName),
  8. CourseDescription: ko.observable(parsedSelectedCourse.CourseDescription),
  9. deleteCourse: function() {
  10. try {
  11. $.ajax({
  12. url: '/Home/Delete',
  13. type: 'POST',
  14. dataType: 'json',
  15. data: ko.toJSON(this),
  16. contentType: 'application/json',
  17. success: successCallback,
  18. error: errorCallback
  19. });
  20. } catch (e) {
  21. window.location.href = '/Home/Read/';
  22. }
  23. }
  24. };
  25. function successCallback(data) {
  26. window.location.href = '/Home/Read/';
  27. }
  28. function errorCallback(err) {
  29. window.location.href = '/Home/Read/';
  30. }
If everything goes fine, you will get a page, as shown below.


delete_page

That’s all for today. You can always download the source code attached to see the complete code and an Application. Happy coding..

References

See also

Conclusion

Did I miss anything that you may think is required? Have you found this post useful? I hope, you liked this article. Please share your valuable suggestions and feedback.

Your turn. What do you think?

A blog isn’t a blog without the 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 E-mail me a link for your question and I’ll definitely try to help, if I can.

Please see this article in my blog here.