Introduction

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 post about MVC
here. 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, 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

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.

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 http://knockoutjs.com/documentation/observables.html" target="_blank">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);

});

Now preceding is our view model and associated functions.

varmodelCreate = {

CourseName: ko.observable(),

CourseDescription: ko.observable(),

createCourse:
function
() {

try{

$.ajax({

url:
'/Home/Create',

type:
'post',

dataType:
'json',

data: ko.toJSON(this),
//Here the data will be converted to JSON

contentType:
'application/json',

success: successCallback,

error: errorCallback

});

}
catch
(e) {

window.location.href =
'/Home/Read/';

}

}

};

functionsuccessCallback(data) {

window.location.href =
'/Home/Read/';

}

functionerrorCallback(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.

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.

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();

});

varmodelView = {

Courses: ko.observableArray([]),

viewCourses:
function
() {

varthisObj = 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.

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

publicActionResult Edit(int? id)

{

if(id == null)

returnnew
HttpStatusCodeResult(HttpStatusCode.BadRequest);

var course = _db.Courses.Find(id);

if(course == null)

returnHttpNotFound();

var serializer =
new
JavaScriptSerializer();

ViewBag.SelectedCourse = serializer.Serialize(course);

returnView();

}

// POST: Home/Update/5

[HttpPost]

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

References

See also

Conclusion

Did we miss anything that you may think which is needed? Could you find this post as useful? Please share us your valuable suggestions and feedback.

Your turn. What do you think?

If you are facing any issues with any codes, please comment here, 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.