My I.T. Side

It's all about web [ASP.NET MVC]

Knockoutjs CRUD

A friend ask me to create a sample CRUD in knockoutjs, so I decided to put it in my blog and share it.

First Step: 
Add knockoutJS to your project you can download it to knockoutjs website then start with view model script.

var viewModel = function(){
    var self = this;

};

$(document).ready(function(){
    var model = new viewModel();

    ko.applyBindings(model);
});


Next the letter C in CRUD, Create. Let's add a html view for our create.

<form data-bind="submit:Create">
    <label>Description</label>
    <input type="hidden" data-bind="value:id">
    <input type="text" data-bind="value:description">
    <input type="submit" value="submit">
</form>

for our create knockoutjs script, Add id and description property as observables. Then function for saving the data into array that is observableArray.

self.list = ko.observableArray([]);
self.id = ko.observable("");
self.description = ko.observable("");
self.action = ko.observable("add");

self.Create = function(){
    if(self.action() == "add"){
        var id = (self.list().length) + 1;
        self.list.push({
           ID:id,
           Description: ko.observable(self.description())
        });
    }
};

Next is Read, and let's add static data in observableArray and read function:

self.data = ko.observableArray([
   {"ID":1, "Description":"Tops"},
   {"ID":2, "Description":"Dresses"},
   {"ID":3, "Description":"Tees"},
   {"ID":4, "Description":"Blouses"},
   {"ID":5, "Description":"Shorts"},
   {"ID":6, "Description":"Pants"},
   {"ID":7, "Description":"Denim"},
   {"ID":8, "Description":"Bags"},
   {"ID":9, "Description":"Jackets"},
   {"ID":10, "Description":"Skirts"},
   {"ID":11, "Description":"Accessories"}]
);

self.Read = function(){
   self.list([]);
   self.list(ko.utils.arrayMap(self.data(),function(item){
      return{
         ID:item.ID,
         Description: ko.observable(item.Description)
      }
   }));
};

Let's add <table> html tag to display our data

<table>
    <thead>
    <th>ID</th>
    <th>Description</th>
    <th>Action</th>
    </thead>
    <tbody data-bind="foreach:list">
    <tr>
        <td data-bind="text:ID"></td>
        <td data-bind="text:Description"></td>
        <td>
            <a href="#" data-bind="click:$root.Delete">Delete</a> | 
            <a href="#" data-bind="click:$root.Edit">Edit</a>
         </td>
    </tr>
    </tbody>
</table>

Now we have a data, let's do an U in CRUD as Update:

self.Edit = function(data){
   self.action("edit");

   self.description(data.Description());
   self.id(data.ID);
};

Then the D as Delete

self.Delete = function(data){
   if(confirm("Are you sure you want to delete this data?")){
      self.list.remove(data);
   }
};

Overall this is what it looks like in fiddle

Overall a simple approach for CRUD in KnockoutJS


Happy Coding!

How to pass data from knockoutjs to ASP.NET MVC view model

You can pass a data using your model in knockoutjs to ASP.NET MVC View model as argument in your action methods.  

First create your model in knockoutjs

var model = function(){
     var self = this:
     self.FirstName = ko.observable();
     self.LastName = ko.observable();
};

Then use this knockout model to pass the data through ajax.

var viewModel = function(){
     var self = this:

     self.Param = new model();
 
     self.SendData = function(){
	var param = ko.toJS(self.Param);
	$.ajax({
            url: "controller/CreateData",
            type: "POST",
            contentType: "application/json; charset=utf-8",
            data: ko.utils.stringifyJson(param),
            success: function (result) {
                //success process in here...
            }
        });
     };
};

Create a viewmodel class:

public class DataViewModel{
    public string FirstName{get;set;}
    public string LastName{get;set;}
}

And in your controller

public ActionResult CreateData(DateViewModel param) {
	//process here..
}

Now you can get the data from args param and use that for your transactions.


Happy Coding