Click here to Skip to main content
15,881,089 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi guys, I am using Knockout Js to do Crud operation in MVC. Select, Add, Delete operations are working fine, but showing an error with Update operation. Error is
-------------------------------------------------------
PUT  XHR   http://localhost:58258/Product/UpdateProduct   [HTTP/1.1 404 Not Found 2ms]
--------------------------
When I click on the above link, it shows following error
-------------------------------------------------
The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.JsonResult UpdateProduct(Int32, MvcWithKnockoutJS.Models.TblProductList)' in 'MvcWithKnockoutJS.Controllers.ProductController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
Parameter name: parameters

What I have tried:

Coding on KnockoutJs file is
-------------------------------

function formatCurrency(value) {
return "₹ " + value.toFixed(2);
}

function ProductViewModel() {
// Make the self as 'this' reference
var self = this;
//Declare observable which will be bind with UI
self.Id = ko.observable("");
self.Name = ko.observable("");
self.Price = ko.observable("");
self.Category = ko.observable("");

var Product = {

Id: self.Id,
Name: self.Name,
Price: self.Price,
Category: self.Category
};

self.Product = ko.observable();
self.Products = ko.observableArray();//contains the list of products

// Initialize the view-model
$.ajax({
url: 'Product/GetAllProducts',
cache: false,
type: 'GET',
contentType: 'application/json; charset=utf-8',
data: {},
success: function (data) {
self.Products(data); // Put the response in ObervableArray
}
});

// Calculate total 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
self.create = function () {
if (Product.Name() != "" && Product.Price() != "" && Product.Category() != "") {
$.ajax({
url: 'Product/AddProduct',
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("");
alert('Product has been added successfully!');
}
}).fail(
function (xhr, textStatus, err) {
alert(err);
});
}
else {
alert('EMPLY FIELDS ARE NOT ALLOWED\n--------------------------------------------------------------\nPlease enter all the values.\nAll fields are required.');
}
}

// 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: id,
success: function (data) {
self.Products.remove(Product);
alert('Product has been deleted!');
}
}).fail(
function (xhr, textStatus, err) {
self.status(err);
});
}
}

// Edit Product Details
self.edit = function (Product) {
self.Product(Product);
}

// Update Product Details
self.update = function () {
var Product = self.Product();
var id = Product.Id;
console.log(id);
if (Product.Name != "" & Product.Price != "" & Product.Category != "") {
$.ajax({
url: 'Product/UpdateProduct',
cache: false,
type: 'PUT',
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 has been updated successfully!');
}
}).fail(function (xhr, textStatus, err) {
alert(err);
});
}
else {
alert('Empty fields are not allowed!');
}
}

// Reset Product Details
self.reset = function () {
self.Name("");
self.Price("");
self.Category("");
}

// Cancel Product Details
self.cancel = function () {
self.Product(null);
}
}
var viewModel = new ProductViewModel();
ko.applyBindings(viewModel);

----------------------------------------------
Coding in Controller Class is
----------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcWithKnockoutJS.Repositories;
using MvcWithKnockoutJS.Models;

namespace MvcWithKnockoutJS.Controllers
{
public class ProductController : Controller
{
// References - https://www.codeproject.com/Tips/1072693/CRUD-in-ASP-NET-MVC-with-KnockOut-JS
static readonly ProductRepository repository = new ProductRepository();
// GET: Product
public ActionResult Products()
{
return View();
}
public JsonResult GetAllProducts()
{
return Json(repository.GetAll(), JsonRequestBehavior.AllowGet);
}
public JsonResult AddProduct(TblProductList item)
{
item = repository.Add(item);
return Json(item, JsonRequestBehavior.AllowGet);
}
public JsonResult UpdateProduct(int id, TblProductList 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 = true }, JsonRequestBehavior.AllowGet);
}
}
}

----------------------------------------------------
Coding in Interface class is
------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MvcWithKnockoutJS.Models;

namespace MvcWithKnockoutJS.Interfaces
{
interface IProductRepository
{
IEnumerable<tblproductlist> GetAll();
TblProductList Get(int id);
TblProductList Add(TblProductList item);
bool Update(TblProductList item);
bool Delete(int id);
}
}

-----------------------------------------------------------------
Coding in Interface Member implementation class
--------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MvcWithKnockoutJS.Interfaces;
using MvcWithKnockoutJS.Models;

namespace MvcWithKnockoutJS.Repositories
{
public class ProductRepository : IProductRepository
{
MvcWithKnockoutJSEntities connectDB = new MvcWithKnockoutJSEntities();

// Implementation of interface member to gett all records from database.
public IEnumerable<tblproductlist> GetAll()
{
// TO DO : Code to get the list of all the records in database
return connectDB.TblProductLists;
}
// Implementation of interface member to get record by Id From Database
public TblProductList Get(int id)
{
// TO DO : Code to find a record in database
return connectDB.TblProductLists.Find(id);
}
// Implementation of interface member to insert data
public TblProductList Add(TblProductList item)
{
if (item == null)
{
throw new ArgumentNullException("item");
}
// TO DO : Code to save record into database
connectDB.TblProductLists.Add(item);
connectDB.SaveChanges();
return item;
}
// Implementation of interface member to update data into database
public bool Update(TblProductList item)
{
if (item == null)
throw new ArgumentNullException("item");
// TO DO : Code to update record into database
var products = connectDB.TblProductLists.Single(a => a.Id == item.Id);
products.Name = item.Name;
products.Category = item.Category;
products.Price = item.Price;
connectDB.SaveChanges();
return true;
}
// Implementation of interface member to delete data from database
public bool Delete(int id)
{
// TO DO : Code to remove the records from database
TblProductList deleteItems = connectDB.TblProductLists.Find(id);
connectDB.TblProductLists.Remove(deleteItems);
return true;
}
}
}
Posted
Updated 9-Mar-17 19:58pm
v4
Comments
Karthik_Mahalingam 10-Mar-17 1:02am    
which line
Ajit Kumar Pandit 10-Mar-17 1:26am    
Following line
------------------------------
// Update Product Details
self.update = function () {
var Product = self.Product();
var id = Product.Id;
console.log(id);
if (Product.Name != "" & Product.Price != "" & Product.Category != "") {
$.ajax({
url: 'Product/UpdateProduct',
cache: false,
type: 'PUT',
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 has been updated successfully!');
}
}).fail(function (xhr, textStatus, err) {
alert(err);
});
}
else {
alert('Empty fields are not allowed!');
}
}
Karthik_Mahalingam 10-Mar-17 1:31am    
what you are getting in var Product = self.Product();
Ajit Kumar Pandit 10-Mar-17 1:37am    
var Product = {

Id: self.Id,
Name: self.Name,
Price: self.Price,
Category: self.Category
};
Karthik_Mahalingam 10-Mar-17 1:50am    
does id and self.id both are same ?

1 solution

UpdateProduct(int id, TblProductList product)

For the UpdateProduct Method you will have to pass id and an object, since id is missing you are getting the error

add this
data: {id:id,product:product},
 
Share this answer
 

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900