Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

MVC CRUD Actions Using KnockoutJS

DZone's Guide to

MVC CRUD Actions Using KnockoutJS

In this post, we'll walk you through a tutorial on how to create an MVC CRUB application using KnockoutJS in conjunction with an SQL database and Visual Studio.

· Web Dev Zone
Free Resource

Learn how to build modern digital experience apps with Crafter CMS. Download this eBook now. Brought to you in partnership with Crafter Software

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 here. Now let’s begin.

Download the Source Code

  • MVC CRUD Actions Using KnockoutJS
  • Introduction to Knockout JS

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

    It has benefits such as:

    • 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).

    • A comprehensive suite of specifications (developed BDD-style) means its correct functioning can easily be verified on 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 that I 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 follows.

    Image title

     add_new_empty_mvc_project 

    Creating a Database and Entity Data Model

    Here I am creating a database with name “TrialDB,” you can always create a DB by running the query given below.

    USE [master]
    GO
    
    /****** Object:  Database [TrialDB]    Script Date: 20-11-2016 03:54:53 PM ******/
    CREATE DATABASE [TrialDB]
     CONTAINMENT = NONE
     ON  PRIMARY
    ( NAME = N'TrialDB', FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL13.SQLEXPRESS\MSSQL\DATA\TrialDB.mdf' , SIZE = 8192KB , MAXSIZE = UNLIMITED, FILEGROWTH = 65536KB )
     LOG ON
    ( 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 )
    GO
    
    ALTER DATABASE [TrialDB] SET COMPATIBILITY_LEVEL = 130
    GO
    
    IF (1 = FULLTEXTSERVICEPROPERTY('IsFullTextInstalled'))
    begin
    EXEC [TrialDB].[dbo].[sp_fulltext_database] @action = 'enable'
    end
    GO
    
    ALTER DATABASE [TrialDB] SET ANSI_NULL_DEFAULT OFF
    GO
    
    ALTER DATABASE [TrialDB] SET ANSI_NULLS OFF
    GO
    
    ALTER DATABASE [TrialDB] SET ANSI_PADDING OFF
    GO
    
    ALTER DATABASE [TrialDB] SET ANSI_WARNINGS OFF
    GO
    
    ALTER DATABASE [TrialDB] SET ARITHABORT OFF
    GO
    
    ALTER DATABASE [TrialDB] SET AUTO_CLOSE OFF
    GO
    
    ALTER DATABASE [TrialDB] SET AUTO_SHRINK OFF
    GO
    
    ALTER DATABASE [TrialDB] SET AUTO_UPDATE_STATISTICS ON
    GO
    
    ALTER DATABASE [TrialDB] SET CURSOR_CLOSE_ON_COMMIT OFF
    GO
    
    ALTER DATABASE [TrialDB] SET CURSOR_DEFAULT  GLOBAL
    GO
    
    ALTER DATABASE [TrialDB] SET CONCAT_NULL_YIELDS_NULL OFF
    GO
    
    ALTER DATABASE [TrialDB] SET NUMERIC_ROUNDABORT OFF
    GO
    
    ALTER DATABASE [TrialDB] SET QUOTED_IDENTIFIER OFF
    GO
    
    ALTER DATABASE [TrialDB] SET RECURSIVE_TRIGGERS OFF
    GO
    
    ALTER DATABASE [TrialDB] SET  DISABLE_BROKER 
    GO
    
    ALTER DATABASE [TrialDB] SET AUTO_UPDATE_STATISTICS_ASYNC OFF
    GO
    
    ALTER DATABASE [TrialDB] SET DATE_CORRELATION_OPTIMIZATION OFF
    GO
    
    ALTER DATABASE [TrialDB] SET TRUSTWORTHY OFF
    GO
    
    ALTER DATABASE [TrialDB] SET ALLOW_SNAPSHOT_ISOLATION OFF
    GO
    
    ALTER DATABASE [TrialDB] SET PARAMETERIZATION SIMPLE 
    GO
    
    ALTER DATABASE [TrialDB] SET READ_COMMITTED_SNAPSHOT OFF
    GO
    
    ALTER DATABASE [TrialDB] SET HONOR_BROKER_PRIORITY OFF
    GO
    
    ALTER DATABASE [TrialDB] SET RECOVERY SIMPLE 
    GO
    
    ALTER DATABASE [TrialDB] SET  MULTI_USER 
    GO
    
    ALTER DATABASE [TrialDB] SET PAGE_VERIFY CHECKSUM  
    GO
    
    ALTER DATABASE [TrialDB] SET DB_CHAINING OFF
    GO
    
    ALTER DATABASE [TrialDB] SET FILESTREAM( NON_TRANSACTED_ACCESS = OFF ) 
    GO
    
    ALTER DATABASE [TrialDB] SET TARGET_RECOVERY_TIME = 60 SECONDS 
    GO
    
    ALTER DATABASE [TrialDB] SET DELAYED_DURABILITY = DISABLED 
    GO
    
    ALTER DATABASE [TrialDB] SET QUERY_STORE = OFF
    GO
    
    USE [TrialDB]
    GO
    
    ALTER DATABASE SCOPED CONFIGURATION SET MAXDOP = 0;
    GO
    
    ALTER DATABASE SCOPED CONFIGURATION FOR SECONDARY SET MAXDOP = PRIMARY;
    GO
    
    ALTER DATABASE SCOPED CONFIGURATION SET LEGACY_CARDINALITY_ESTIMATION = OFF;
    GO
    
    ALTER DATABASE SCOPED CONFIGURATION FOR SECONDARY SET LEGACY_CARDINALITY_ESTIMATION = PRIMARY;
    GO
    
    ALTER DATABASE SCOPED CONFIGURATION SET PARAMETER_SNIFFING = ON;
    GO
    
    ALTER DATABASE SCOPED CONFIGURATION FOR SECONDARY SET PARAMETER_SNIFFING = PRIMARY;
    GO
    
    ALTER DATABASE SCOPED CONFIGURATION SET QUERY_OPTIMIZER_HOTFIXES = OFF;
    GO
    
    ALTER DATABASE SCOPED CONFIGURATION FOR SECONDARY SET QUERY_OPTIMIZER_HOTFIXES = PRIMARY;
    GO
    
    ALTER DATABASE [TrialDB] SET  READ_WRITE 
    GO


    Create a Table

    To create a table, you can run the query below.

    USE [TrialDB]
    GO
    
    /****** Object:  Table [dbo].[Course]    Script Date: 20-11-2016 03:57:30 PM ******/
    SET ANSI_NULLS ON
    GO
    
    SET QUOTED_IDENTIFIER ON
    GO
    
    CREATE TABLE [dbo].[Course](
        [CourseID] [int] NOT NULL,
        [CourseName] [nvarchar](50) NOT NULL,
        [CourseDescription] [nvarchar](100) NULL,
     CONSTRAINT [PK_Course] PRIMARY KEY CLUSTERED 
    (
        [CourseID] 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


    So our database is ready. Now we will create an Entity Data Model with the database we created.

    Image title

     create_entity_data_model 

    Install Knockout JS

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

    Image title

     install_knockout 

    Now let us start our coding as everything is set.

    C – Create Operation

    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.

    // GET: Home/Create
           public ActionResult Create()
           {
               return View();
           }
    
           // POST: Home/Create
           [HttpPost]
           public string Create(Course course)
           {
               if (!ModelState.IsValid) return "Model is invalid";
               _db.Courses.Add(course);
               _db.SaveChanges();
               return "Cource is created";
           }


    Here, the first action calls the view for the create operation and the second operation inserts the data into the database. And _db is our entity.

     private readonly TrialDBEntities _db = new TrialDBEntities(); 

    Now let’s go ahead and create a view for the Create operation.

    @model MVCCRUDKnockout.Models.Course
    
    @{
        ViewBag.Title = "Create";
    }
    
    <div class="form-horizontal">
        <h4>Course</h4>
        <hr>
    
        <div class="form-group">
            <label class="control-label col-md-2" for="CourseName">CourseName</label>
            <div class="col-md-10">
                <input class="form-control text-box single-line" id="CourseName" name="CourseName" type="text" value="" data-bind="value: CourseName">
            </div>
        </div>
    
        <div class="form-group">
            <label class="control-label col-md-2" for="CourseDescription">CourseDescription</label>
            <div class="col-md-10">
                <input class="form-control text-box single-line" id="CourseDescription" name="CourseDescription" type="text" value="" data-bind="value: CourseDescription">
            </div>
        </div>
    
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="button" data-bind="click: createCourse" value="Create" class="btn btn-default">
            </div>
        </div>
    </div>
    
    <div>
        @Html.ActionLink("Back to List", "Read")
    </div>
    <script src="~/Scripts/jquery-1.10.2.min.js"></script>
    <script src="~/Scripts/knockout-3.4.0.js"></script>
    <script src="~/Scripts/KOScripts/KOCreate.js"></script>


    Did you notice that we are binding data to our input controls as data-bind=”value: CourseName”? This value is related to the view model we are going to set. The interesting thing about this is, the values in the model will get changed as you change the values in the input. You don’t need to add any kind of code for that operation.

    Lastly, we bind a click event as follows:

     <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 an MVVM pattern and now lets us read some basic information provided in the Knockout JS documentation.

    MVVM and View Models

    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:

    1. A model: 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.

    2. A view model: 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. 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 – 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.

    3. A view: 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.

    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.

    Now back to our Create operation: KOCreate.js is the file in which we are going to write our operation. Now please open that file and bind view model as follows:

    $(function () {
        ko.applyBindings(modelCreate);
    });


    Image title

     knockout_apply_bindings 

    Now, the following is our view model and associated functions:

    var modelCreate = {
        CourseName: ko.observable(),
        CourseDescription: ko.observable(),
        createCourse: function () {
            try {
                $.ajax({
                    url: '/Home/Create',
                    type: 'post',
                    dataType: 'json',
                    data: ko.toJSON(this), //Here the data wil be converted to JSON
                    contentType: 'application/json',
                    success: successCallback,
                    error: errorCallback
                });
            } catch (e) {
                window.location.href = '/Home/Read/';
            }
        }
    };
    
    function successCallback(data) {
        window.location.href = '/Home/Read/';
    }
    function errorCallback(err) {
        window.location.href = '/Home/Read/';
    }


    Here ko.observable() 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 observable(). Now please run your view and check whether it is working fine.

    Image title


     create_page 

    R – Read Operation

    As we have completed our Create operation, now it is time for Read. Please open your controller and write the actions as follows:

    // GET: Home
            public ActionResult Read()
            {
                return View();
            }
    
            //GET All Courses
            public JsonResult ListCourses()
            {
                return Json(_db.Courses.ToList(), JsonRequestBehavior.AllowGet);
            }


    You can create your Read view as follows:

    @{
        ViewBag.Title = "Read";
    }
    
    <h2>Index</h2>
    
    <p>
        @Html.ActionLink("Create New", "Create")
    </p>
    <table class="table">
        <tr>
            <th>
                Course Name
            </th>
            <th>
                Course Description
            </th>
            <th></th>
        </tr>
        <tbody data-bind="foreach: Courses">
        <tr>
            <td data-bind="text: CourseName"></td>
            <td data-bind="text: CourseDescription"></td>
            <td>
                <a data-bind="attr: { 'href': '@Url.Action("Edit", "Home")/' + CourseID }" class="btn-link">Edit</a>
                <a data-bind="attr: { 'href': '@Url.Action("Delete", "Home")/' + CourseID }" class="btn-link">Delete</a>
            </td>
        </tr>
        </tbody>
    </table>
    <script src="~/Scripts/jquery-1.10.2.min.js"></script>
    <script src="~/Scripts/knockout-3.4.0.js"></script>
    <script src="~/Scripts/KOScripts/KORead.js"></script>
    Here we are using data-bind=”foreach: Courses” for looping through our model we are going to create 


    Here we are using data-bind=”foreach: Courses” for looping through our model that we are going to create now. So shall we do that? Please create a JS file with name KORead.js and add the following code:

    $(function () {
        ko.applyBindings(modelView);
        modelView.viewCourses();
    });
    
    var modelView = {
        Courses: ko.observableArray([]),
        viewCourses: function () {
            var thisObj = this;
            try {
                $.ajax({
                    url: '/Home/ListCourses',
                    type: 'GET',
                    dataType: 'json',
                    contentType: 'application/json',
                    success: function (data) {
                        thisObj.Courses(data); //Here we are assigning values to KO Observable array
                    },
                    error: function (err) {
                        alert(err.status + " : " + err.statusText);
                    }
                });
            } catch (e) {
                window.location.href = '/Home/Read/';
            }
        }
    };


    Here goes the output:

    Image title

      read_page 

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

    U – Update Operation

    As we did for the above two operations, let us create some actions in our controller first.

    // GET: Home/Edit/5
            public ActionResult Edit(int? id)
            {
                if (id == null)
                    return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
                var course = _db.Courses.Find(id);
                if (course == null)
                    return HttpNotFound();
                var serializer = new JavaScriptSerializer();
                ViewBag.SelectedCourse = serializer.Serialize(course);
                return View();
            }
    
            // POST: Home/Update/5
            [HttpPost]
            public string Update(Course course)
            {
                if (!ModelState.IsValid) return "Invalid model";
                _db.Entry(course).State = EntityState.Modified;
                _db.SaveChanges();
                return "Updated successfully";
            }


    Here, the first action with parameter ID is called whenever a user clicks on the Edit link from the table we created. And 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 follows:

    @{
        ViewBag.Title = "Edit";
    }
    
    <h2>Edit</h2>
    
    
    @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()
    
        <div class="form-horizontal">
            <h4>Course</h4>
    
            <div class="form-group">
                <label class="control-label col-md-2" for="CourseName">CourseName</label>
                <div class="col-md-10">
                    <input class="form-control text-box single-line" id="CourseName" name="CourseName" type="text" value="" data-bind="value: CourseName">
                </div>
            </div>
    
            <div class="form-group">
                <label class="control-label col-md-2" for="CourseDescription">CourseDescription</label>
                <div class="col-md-10">
                    <input class="form-control text-box single-line" id="CourseDescription" name="CourseDescription" type="text" value="" data-bind="value: CourseDescription">
                </div>
            </div>
    
            <div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                    <input type="button" data-bind="click: updateCourse" value="Update" class="btn btn-default">
                </div>
            </div>
        </div>
    }
    <script type="text/javascript">
        var selectedCourse = '@Html.Raw(ViewBag.selectedCourse)';
    </script>
    <div>
        @Html.ActionLink("Back to List", "Read")
    </div>
    <script src="~/Scripts/jquery-1.10.2.min.js"></script>
    <script src="~/Scripts/knockout-3.4.0.js"></script>
    <script src="~/Scripts/KOScripts/KOUpdate.js"></script>


    And create a JS with name KOUpdate.js and add the following code:

    var parsedSelectedCourse = $.parseJSON(selectedCourse);
    $(function () {
        ko.applyBindings(modelUpdate);
    });
    
    var modelUpdate = {
        CourseID: ko.observable(parsedSelectedCourse.CourseID),
        CourseName: ko.observable(parsedSelectedCourse.CourseName),
        CourseDescription: ko.observable(parsedSelectedCourse.CourseDescription),
        updateCourse: function () {
            try {
                $.ajax({
                    url: '/Home/Update',
                    type: 'POST',
                    dataType: 'json',
                    data: ko.toJSON(this),
                    contentType: 'application/json',
                    success: successCallback,
                    error: errorCallback
                });
            } catch (e) {
                window.location.href = '/Home/Read/';
            }
        }
    };
    
    function successCallback(data) {
        window.location.href = '/Home/Read/';
    }
    function errorCallback(err) {
        window.location.href = '/Home/Read/';
    }


    Now, run your application and see the Edit/Update operation.

    Image title

     edit_page 

    D – Delete Operation

    So our last operation, Delete. Let’s edit our controller as follows:

    // GET: Home/Delete/5
            public ActionResult Delete(int? id)
            {
                if (id == null)
                    return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
                var course = _db.Courses.Find(id);
                if (course == null)
                    return HttpNotFound();
                var serializer = new JavaScriptSerializer();
                ViewBag.SelectedCourse = serializer.Serialize(course);
                return View();
            }
    
            // POST: Home/Delete/5
            [HttpPost, ActionName("Delete")]
            public string Delete(Course course)
            {
                if (course == null) return "Invalid data";
                var getCourse = _db.Courses.Find(course.CourseID);
                _db.Courses.Remove(getCourse);
                _db.SaveChanges();
                return "Deleted successfully";
            }


    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.

    @model MVCCRUDKnockout.Models.Course
    
    @{
        ViewBag.Title = "Delete";
    }
    
    <h2>Delete</h2>
    
    <h3>Are you sure you want to delete this?</h3>
    @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()
    
        <div class="form-horizontal">
            <h4>Course</h4>
    
            <div class="form-group">
                <label class="control-label col-md-2" for="CourseName">CourseName</label>
                <div class="col-md-10">
                    <input class="form-control text-box single-line" id="CourseName" name="CourseName" type="text" value="" data-bind="value: CourseName">
                </div>
            </div>
    
            <div class="form-group">
                <label class="control-label col-md-2" for="CourseDescription">CourseDescription</label>
                <div class="col-md-10">
                    <input class="form-control text-box single-line" id="CourseDescription" name="CourseDescription" type="text" value="" data-bind="value: CourseDescription">
                </div>
            </div>
    
            <div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                    <input type="button" data-bind="click: deleteCourse" value="Delete" class="btn btn-default">
                </div>
            </div>
        </div>
    }
    <script type="text/javascript">
        var selectedCourse = '@Html.Raw(ViewBag.selectedCourse)';
    </script>
    <div>
        @Html.ActionLink("Back to List", "Read")
    </div>
    <script src="~/Scripts/jquery-1.10.2.min.js"></script>
    <script src="~/Scripts/knockout-3.4.0.js"></script>
    <script src="~/Scripts/KOScripts/KODelete.js"></script>


    And you can always create our Knockout codes as follows:

    ar parsedSelectedCourse = $.parseJSON(selectedCourse);
    $(function () {
        ko.applyBindings(modelDelete);
    });
    
    var modelDelete = {
        CourseID: ko.observable(parsedSelectedCourse.CourseID),
        CourseName: ko.observable(parsedSelectedCourse.CourseName),
        CourseDescription: ko.observable(parsedSelectedCourse.CourseDescription),
        deleteCourse: function () {
            try {
                $.ajax({
                    url: '/Home/Delete',
                    type: 'POST',
                    dataType: 'json',
                    data: ko.toJSON(this),
                    contentType: 'application/json',
                    success: successCallback,
                    error: errorCallback
                });
            } catch (e) {
                window.location.href = '/Home/Read/';
            }
        }
    };
    
    function successCallback(data) {
        window.location.href = '/Home/Read/';
    }
    function errorCallback(err) {
        window.location.href = '/Home/Read/';
    }


    If everything goes fine, you will get a page as follows:

    Image title

     delete_page 

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

    References

  • Knockout JS
  • Knockout JS Observables
  • See Also

  • External links and tutorials
  • Conclusion

    Did I miss anything that you may think is needed? Did you find this post as useful? I hope you liked this article. Please share me your valuable suggestions and feedback.

    Crafter is a modern CMS platform for building modern websites and content-rich digital experiences. Download this eBook now. Brought to you in partnership with Crafter Software.

    Topics:
    web dev ,knockout.js ,javascript ,sql

    Published at DZone with permission of Sibeesh Venu, DZone MVB. See the original article here.

    Opinions expressed by DZone contributors are their own.

    THE DZONE NEWSLETTER

    Dev Resources & Solutions Straight to Your Inbox

    Thanks for subscribing!

    Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

    X

    {{ parent.title || parent.header.title}}

    {{ parent.tldr }}

    {{ parent.urlSource.name }}