Friday 20 February 2015

Kendo-Knockout Reference Example with MVC

Product Repository

   interface IProductRepository : IDisposable
    {
        IEnumerable<Product> GetAll();
        Product Get(int id);
        Product Add(Product item);
        bool Update(Product item);
        bool Delete(int id);
        void Save();
    }

  public class ProductRepository : IProductRepository, IDisposable
    {

        RepositoryEntities context = null;
  
        public ProductRepository()
        {
            context = new RepositoryEntities();
        }

        public ProductRepository(RepositoryEntities context)
        {
            this.context = context;
        }

        public IEnumerable<Product> GetAll()
        {
           return context.Products.ToList();
        }

        public Product Get(int id)
        {
            return context.Products.Find(id);
        }

        public Product Add(Product item)
        {
            Product newProduct = context.Products.Add(item);
            int id = context.SaveChanges();
            return newProduct;
        }

        public bool Update(Product item)
        {
            context.Entry(item).State = EntityState.Modified;
            context.SaveChanges();
            return true;
        }

        public bool Delete(int id)
        {
            Product objProduct = context.Products.Find(id);
            context.Products.Remove(objProduct);
            context.SaveChanges();
            return true;
        }

        public void Save()
        {
            context.SaveChanges();
        }

        private bool disposed = false;

        protected virtual void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {
                    context.Dispose();
                }
            }
            this.disposed = true;
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
    }



Controller

public class ProductController : Controller
    {
       // private IProductRepository productRepository;
        private IProductRepository repository = new ProductRepository();
     

        //public ProductController(IProductRepository repository)
        //{
        //    this.productRepository = repository;
        //}


        //
        // GET: /Product/
        public ActionResult Index()
        {
            return View();
        }

        public JsonResult GetProoducts()
        {
            return Json(repository.GetAll(), JsonRequestBehavior.AllowGet);
        }

        public JsonResult AddProduct(Product item)
        {
            item = repository.Add(item);
            return Json(item, JsonRequestBehavior.AllowGet);
        }

        public JsonResult EditProduct(int id, Product product)
        {
            product.Id = id;
            if (repository.Update(product))
            {
                return Json(repository.GetAll(), JsonRequestBehavior.AllowGet);
            }

            return Json(null);
        }


        public JsonResult DeleteProduct(int id)
        {
            if (repository.Delete(id))
            {
                return Json(new { Status = true }, JsonRequestBehavior.AllowGet);
            }

            return Json(new { Status = false }, JsonRequestBehavior.AllowGet);
        }
    }


View


@{
    ViewBag.Title = "Index";
}


<script src="~/jquery.min.js"></script>
<script src="~/kendo.all.min.js"></script>
<script src="~/knockout-3.1.0.js"></script>
<script src="~/knockout-kendo.min.js"></script>
<link href="~/kendo.silver.min.css" rel="stylesheet" />


<div id="body">
    <h2>Kendo Knockout CRUD Operations</h2>
    <div data-bind="kendoGrid: { data : Products,  rowTemplate: 'rowTmpl', scrollable: true, sortable: true, useKOTemplates: true}">
    </div>
    <script id="rowTmpl" type="text/html">
        <tr>
            <td data-bind="text: Id"></td>
            <td data-bind="text: Name"></td>
            <td data-bind="text: Price"></td>
            <td data-bind="text: Category"></td>
            <td> <button data-bind="click: $root.Edit">Edit</button></td>
            <td> <button data-bind="click: $root.Delete">Delete</button></td>
</tr>
    </script>
    <br/>
    <div data-bind="if: Product">
        <div>
            <h2>Update Product</h2>
        </div>
        <div>
            <label for="productId" data-bind="visible: false">ID</label>
            <label data-bind="text: Product().Id, visible: false"></label>
        </div>
        <div>
            <label for="name">Name</label>
            <input data-bind="value: Product().Name" type="text" title="Name" />
        </div>
        <div>
            <label for="category">Category</label>
            <input data-bind="value: Product().Category" type="text" title="Category" />
        </div>
        <div>
            <label for="price">Price</label>
            <input data-bind="value: Product().Price" type="text" title="Price" />
        </div>
        <br />
        <div>
            <button data-bind="click: $root.Update">Update</button>
            <button data-bind="click: $root.Cancel">Cancel</button>
        </div>
    </div>
    <br />
    <div data-bind="ifnot: Product()">
            <div>
                <h2>Add New Product</h2>
            </div>
            <div>
                <label for="name">Name</label>
                <input data-bind="value: $root.Name" type="text" title="Name" />
            </div>
            <div>
                <label for="price">Price</label>
                <input data-bind="value: $root.Price" type="text" title="Price" />
            </div>
            <div>
                <label for="category">Category</label>
                <input data-bind="value: $root.Category" type="text" title="Category" />
            </div>
            <div>
                <button data-bind="click: $root.Create">Save</button>
                <button data-bind="click: $root.Reset">Reset</button>
            </div>
        </div>
    </div>


<script type="text/javascript">
    $(document).ready(function () {
        var ViewModel = function () {
            var self = this;

            self.Id = ko.observable();
            self.Name = ko.observable();
            self.Category = ko.observable();
            self.Price = ko.observable();

            var Product = {
                Id: self.Id,
                Name: self.Name,
                Category: self.Category,
                Price: self.Price
            };

            self.Product = ko.observable();
            self.Products = ko.observableArray();

            $.getJSON("/Product/GetProoducts", function (data) {
                self.Products(data);
                $.each(data, function (index) {

                 })
            });


            self.Create = function () {
                if (Product.Name() != "" && Product.Price() != "" && Product.Category() != "") {
                    $.ajax({
                        url: '@Url.Action("AddProduct", "Product")',
                        cache: false,
                        type: 'POST',
                        contentType: 'application/json; charset=utf-8',
                        data: ko.toJSON(Product),
                        success: function (data) {
                            self.Products.push(data);
                            self.Name("");
                            self.Price("");
                            self.Category("");

                        }
                    }).fail(function (xhr, textStatus, err) {
                        alert(err);
                    });
                }
            }


            self.Reset = function () {
                self.Name("");
                self.Price("");
                self.Category("");
            }


            // Edit product details
            self.Edit = function (Product) {
                self.Product(Product);
            }


            // Cancel product Details
            self.Cancel = function () {
                self.Product(null);
            }

            //Update Product Details
            self.Update = function () {
                var Product = self.Product();

                $.ajax({
                    url: '@Url.Action("EditProduct", "Product")',
                    cache: false,
                    type: 'POST',
                    contentType: 'application/json; charset=utf-8',
                    data: ko.toJSON(Product),
                    success: function (data) {
                        self.Products.removeAll();
                        self.Products(data); //Put the response in ObservableArray
                        self.Product(null);
                        alert("Record Updated Successfully");
                    }
                }).fail(function (xhr, textStatus, err) { alert(err); });
            }


            //Delete  Product Details
            self.Delete = function (Product) {
                if (confirm('Are you sure to Delete "' + Product.Name + '" product ??'))
                {
                    var id = Product.Id;

                    $.ajax({
                        url: '/Product/DeleteProduct/'+ id,
                        cache: false,
                        type: 'POST',
                        contentType: 'application/json; charset=utf-8',
                        data: ko.toJSON(id),
                        success: function (data) {
                            self.Products.remove(Product);

                        }
                    }).fail(
                    function (xhr, textStatus, err) {
                        self.status(err);
                    });
                }
            }
        }

        ko.applyBindings(new ViewModel());
    });
</script>

Reference Links