Click here to Skip to main content
15,867,453 members
Articles / All Topics
Technical Blog

MVC CRUD Actions Using Knockout JS

Rate me:
Please Sign up or sign in to vote.
4.67/5 (3 votes)
11 Dec 2016CPOL7 min read 8.2K   5   2
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’s begin.

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’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 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.

    It has benefits 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)
    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 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.

    Create an Empty MVC application

    To get started we will create an empty MVC application as follows.

    add_new_empty_mvc_project

    add_new_empty_mvc_project

    Creating 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.

    create_entity_data_model

    create_entity_data_model

    Install Knockout JS

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

    install_knockout

    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 insert the data to database. And _db is our entity.

    private readonly TrialDBEntities _db = new TrialDBEntities();

    Now let’s go ahead and create view for 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 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 codes for that operations.

    At last we are binding a click event as follows right?

    <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 for building user interfaces. It describes how you can keep a potentially sophisticated UI simple by splitting it into three parts:

    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.

    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.

    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 we are going to write our operation. Now please open that file and bind view model as follows.

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

    knockout_apply_bindings

    Now preceding 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.

    create_page

    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 preceding.

    @{
        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 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.

    read_page

    read_page

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

    U – Update operation

    As we did for the above two operation, 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 click on 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.

    edit_page

    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 preceding.

    var 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.

    delete_page

    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 which is needed? Could you find this post as useful? I hope you liked this article. Please share me your valuable suggestions and feedback.

    Your turn. What do you think?

    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.

    Kindest Regards
    Sibeesh Venu

    License

    This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


    Written By
    Software Developer
    Germany Germany
    I am Sibeesh Venu, an engineer by profession and writer by passion. I’m neither an expert nor a guru. I have been awarded Microsoft MVP 3 times, C# Corner MVP 5 times, DZone MVB. I always love to learn new technologies, and I strongly believe that the one who stops learning is old.

    My Blog: Sibeesh Passion
    My Website: Sibeesh Venu

    Comments and Discussions

     
    QuestionMinor stuff Pin
    John Perryn4-Jan-17 14:20
    John Perryn4-Jan-17 14:20 
    AnswerRe: Minor stuff Pin
    Sibeesh Passion5-Jan-17 5:24
    professionalSibeesh Passion5-Jan-17 5:24 

    General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

    Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.