---
title: "How to Insert Data in database using Knockout.js."  
description: "How to Insert Data in database using Knockout.js."  
author: "Anonymous User"  
published: 2015-10-26  
updated: 2015-10-26  
canonical: https://www.mindstick.com/forum/33538/how-to-insert-data-in-database-using-knockout-js  
category: ".net"  
tags: ["knockout.js", "knockout mvc"]  
reading_time: 4 minutes  

---

# How to Insert Data in database using Knockout.js.

Can [anyone](https://www.mindstick.com/articles/23207/how-to-find-the-best-fit-job-for-anyone) please help me how to [solve this problem](https://answers.mindstick.com/qa/94681/my-google-assistant-shows-completely-different-search-results-from-what-i-ask-how-can-i-solve-this-problem).

## Replies

### Reply by Anonymous User

```
1.  Create a View <script src="/Scripts/jquery-2.1.4.js"></script>      <script src="/Scripts/bootstrap.js"></script>
 <script src="/Scripts/knockout-3.1.0.js"></script>
<div class="modal fade" id="AddNewModel" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog
modal-lg" role="document">
<div class="modal-content" id="model-confirmation-content">
  <div class="modal-header">
   <button type="button" class="close" data-dismiss="modal" aria-label="Close">
   <span aria-hidden="true">&times;</span></button>
   <h4 class="modal-title">Add New Product</h4>
   </div>
    <div class="modal-body">
     <div class="form-horizontal">
      <div class="form-group">
      <label for="concept" class="col-sm-3 control-label">Category</label>
      <div class="col-sm-9">
      <select class="form-control" id="category" data-bind="options:CategoryList,       
optionsText:'CategotyName',optionsValue:'CategoryId', value:CategotyId ,
optionsCaption: 'Choose...', event:{ change:ChangeCategory}">
          </select>
           </div>
          </div>
          <div class="form-group">
         <label for="description" class="col-sm-3 control-label">Product Name</label>
          <div class="col-sm-9">
          <select class="form-control" data-bind="options: ProductList,optionsText: 'ProductName',optionsValue: 'ProductId',value:ProductId,optionsCaption: 'Choose...',event:{ change:ProductCategory}">
           </select>
          </div>
          </div>
           <div class="form-group">
             <label for="amount" class="col-sm-3 control-label">Price</label>
              <div class="col-sm-9">
 <input type="text"  class="form-control"  data-bind="value:Price"  readonly id="price" name="Price">   </div>
   </div>
    <div class="form-group">
    <label for="status" class="col-sm-3 control-label">Quntity</label>
    <div class="col-sm-9">
     <input type="number" id="Qty" class="form-control" data-bind="value:
                                 Quantity" id="Quntity" name="Quntity" required">
                            </div>
                        </div>
                        <div class="form-group">
 <label for="date" class="col-sm-3 control-label">Amount</label>
                            <div class="col-sm-9">
                                <input type="text" class="form-control" data-bind="value:  TotalAmount" readonly id="amount" name="amount">
                            </div>
                        </div>
                        <div class="form-group">
                            <div class="col-sm-12 text-right">
                                <button type="button" class="btn btn-default
preview-add-button"  data-bind="click:$root.Insert">
                                    <span class="glyphicon glyphicon-plus"></span>Add
                                </button>
                            </div>
                        </div>
                    </div>
                  <div class="table-responsive">
                            <table class="table table-hover">
                                <thead>
                                    <tr>
                                        <th>ProductId</th>
                                        <th>Product Name</th>
                                        <th>Category</th>
                                        <th>Price</th>
                                        <th>Quantity</th>
                                        <th>Amount</th>
                                    </tr>
                                </thead>
                                <tbody data-bind="foreach: Products">
                                    <tr>
                                        <td data-bind="text: ProductId"></td>
                                        <td data-bind="text: ProductName"></td>
                                        <td data-bind="text: CategotyName"></td>
                                        <td data-bind="text: Price"></td>
                                        <td data-bind="text: Quantity"></td>
                                        <td data-bind="text: TotalAmount"></td>
                                        <td>   <button data-bind="click: $root.delete"  class="btn btn-danger">Delete</button>                                        </td>                                    </tr>
                                </tbody>
                                <!-- preview content goes here-->
                            </table>
                        </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-primary " data-bind="event:{
                     click:Save}">Save</button>&nbsp;&nbsp;
                    <button type="button" class="btn btn-danger " data-bind="event:{
                       click:Cancel }">Cancel</button>
                </div>
            </div>
        </div>
    </div>
```

```
<script>
function Product(data) {
    this.Id = ko.observable(data.Id);
    this.ProductId = ko.observable(data.ProductId);
    this.CategotyName = ko.observable(data.CategotyName);
    this.ProductName = ko.observable(data.ProductName);
    this.Price = ko.observable(data.Price);
    this.CategotyId = ko.observable(data.CategotyId);
    this.Quantity = ko.observable(data.Quantity)
    this.TotalAmount = ko.observable(data.TotalAmount);
}

function ProductViewModel() {
    //Make
the self as 'this' reference
    var self = this;
    self.Id = ko.observable();
    self.ProductId = ko.observable();
    self.CategotyName = ko.observable();
    self.ProductName = ko.observable();
    self.Price = ko.observable(0);
    self.CategotyId = ko.observable();
    self.Quantity = ko.observable();
    self.TotalAmount = ko.computed(function () {
        return this.Quantity() * this.Price();
    }, this);

    self.Products = ko.observableArray();
    self.ProductList = ko.observableArray();
    self.CategoryList = ko.observableArray();
    self.CustomerProducts =ko.observableArray();
    self.errors = ko.validation.group(this, { deep: true, observable: false });
    $.getJSON("/Product/GetCategoty", function (data) {
        self.CategoryList(data);
    });
    self.ChangeCategory = function () {
        $.getJSON("/Product/GetProduct", { categoryId: self.CategotyId }, function (data) {
            self.ProductList(data);
        });
    }
    self.ProductCategory = function () {
        $.getJSON("/Product/GetProductDetails", { ProductId: self.ProductId }, function (data) {
            self.Price(data[0].Price);
            self.ProductName(data[0].ProductName);           
self.CategotyName(data[0].CategotyName);
        });
    }
    //
Calculate Total of Price After Initialization
    self.Total = ko.computed(function () {
        var sum = 0;
        var arr = self.Products();
        for (var i = 0; i < arr.length; i++) {
            sum += arr[i].Price();
        }
        return sum;
    });
    }
    //Add
New Item in List
   self.Insert = function () {
       if (self.errors().length > 0) {
            self.errors.showAllMessages();
            return;
        }
        self.Products.push(new Product({
            Id: self.Id(),
            ProductId: self.ProductId(),
            ProductName: self.ProductName(),
            CategotyName: self.CategotyName(),
            CategotyId: self.CategotyId(),
            Price: self.Price(),
            Quantity: self.Quantity(),
            TotalAmount: self.TotalAmount()
        }));
        self.Id(null);
        self.ProductId(null);
        self.CategotyName(null);
        self.ProductName(null);
        self.Price(null);
        self.CategotyId(null);
        self.Quantity(null);
        self.errors.showAllMessages(false);
    }
//
save product in database

         self.Save = function () {
        var data = ko.toJSON(self.Products());
        $.ajax({
            url: '/Product/Insert',
            cache: false,
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            data: data,
            success: function (data) {
                self.Products.removeAll();
             $('#AddNewModel').modal('hide');
            }
        }).fail(

 function (xhr, textStatus, err) {
     alert(err);
 });
   //
Delete product details
    self.Cancel = function () {
        self.Products.removeAll();  
    }}
$(function () {
    var productViewModel = new ProductViewModel();
    ko.applyBindings(productViewModel);
});
</script>
```

```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ProductManagement.Models;
namespace ProductManagement.Controllers
{    public class GenericController : Controller
    {
        IGenericReposity<ProductDetail> _productDetails;
        public GenericController()
        {
            _productDetails = new GenericReposity<ProductDetail>(new ProductDBEntities());
        }
        public ActionResult Index()
        {
            return View();
        }
        public void Insert(IList<ProductDetail> obj)
        {
            foreach (ProductDetail o in obj)
            {                _productDetails.Add(o);
                _productDetails.Save();
            }
        }
    }
}
```

```

```


---

Original Source: https://www.mindstick.com/forum/33538/how-to-insert-data-in-database-using-knockout-js

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
