可选参数必须是引用类型,可空类型,或者声明为可选参数。 [英] An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
问题描述
大家好,我正在使用Knockout Js在MVC中进行Crud操作。选择,添加,删除操作正常,但显示更新操作时出错。错误是
---------------------------------------- ---------------
PUT XHR http:// localhost:58258 / Product / UpdateProduct [ HTTP / 1.1 404未找到2ms]
--------------------------
当我点击上面的链接时,它显示以下错误
------------------------------ -------------------
参数字典包含非可空类型'System.Int32'的参数'id'的空条目'MvcWithKnockoutJS.Controllers.ProductController'中的方法'System.Web.Mvc.JsonResult UpdateProduct(Int32,MvcWithKnockoutJS.Models.TblProductList)'。可选参数必须是引用类型,可以为空的类型,或者声明为可选参数。
参数名称:参数
< b>我尝试了什么:
KnockoutJs文件的编码是
---------- ---------------------
函数格式货币(价值){
返回₹+ value.toFixed(2);
}
函数ProductViewModel(){
//将self设为'this'参考
var self = this;
//声明将与UI绑定的observable
self.Id = ko.observable();
self.Name = ko.observable();
self.Price = ko.observable( );
self.Category = ko.observable();
var Product = {
Id:self.Id,
姓名:self.Name,
价格:self.Price,
类别:self.Category
};
self.Product = ko.observable();
self.Products = ko。 observableArray(); //包含产品列表
//初始化视图模型
$ .ajax({
url:'Product / GetAllProducts',
cache:false,
类型:'GET',
contentType:'应用/ JSON; charset = utf-8',
数据:{},
成功:函数(数据){
self.Products(data); //将响应放入ObervableArray
}
});
//初始化后计算总价
self.Total = ko.computed(function(){
var sum = 0;
var arr = self.Products();
for(var i = 0; i< arr.length; i ++){
sum + = arr [i] .Price;
}
返还金额;
});
//添加新商品
self.create = function(){
if(Product.Name()!=&& Product.Price()!=&&& Product.Category ()!=){
$ .ajax({
url:'Product / AddProduct',
cache:false,
类型:'POST',
contentType:'application / json; charset = utf-8',
data:ko.toJSON(Product ),
succ ess:function(data){
self.Products.push(data);
self.Name();
self。价格();
self.Category();
alert('产品已成功添加!');
}
})。失败(
函数(xhr,textStatus,错误){
alert(错误);
});
}
else {
alert('EMPLY FIELDS不允许'------- -------------------------------------------------- ----- \ n请输入所有值。\ n所有字段都是必填项。');
}
}
< br $>
//删除产品详细信息
self.delete = function(产品){
if(确认('你确定要删除''+ Product.Name +'product ??')){
var id = Product.Id;
$ .ajax({
url:'Product / DeleteProduct /'+ id,
cache:false,
类型:'POST',
contentType:'application / json; charset = utf-8',
数据:id,
成功:函数(数据){
self.Products.remove(Product) ;
alert('产品已被删除!');
}
})。失败(
function(xhr,textStatus,err){
self.status(err);
});
}
}
//编辑产品详情
self.edit = function(产品){
self .Product(产品);
}
//更新产品详情
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',
数据:ko.toJSON(产品),
成功:功能(数据){
self.Products .removeAll();
self.Products(data); //将响应放在observableArray中
self.Product(null);
alert('记录已成功更新!')
}
})。失败(函数(xhr,textStatus,错误){
alert(错误);
});
}
else {
alert('不允许空字段!');
}
}
//重置产品详情
self.reset = function(){
self .Name();
self.Price();
self.Category();
}
//取消产品详情
self.cancel = function(){
self.Product(null);
}
}
var viewModel = new ProductViewModel();
ko.applyBindings(viewModel); < br $> b $ b
------------------ ----------------------------
控制器类编码是
- ---------------------------------------------
使用System;
使用System.Collections.Generic;
使用System.Linq;
使用System.Web;
使用System.Web.Mvc;
使用MvcWithKnockoutJS.Repositories;
使用MvcWithKnockoutJS.Models;
名称空间MvcWithKnockoutJS.Controllers
{
公共类ProductController:控制器
{
//参考文献 - https://www.codeproject.com/Tips/1072693/CRUD-in-ASP-NET-MVC-with-KnockOut-JS
静态只读ProductRepository repository = new ProductRepository();
//获取:产品
公共ActionResult产品()
{
返回查看();
}
public JsonResult GetAllProducts()
{
返回Json(repository.GetAll(),JsonRequestBehavior.AllowGet);
}
public JsonResult AddProduct(TblProductList item)
{
item = repository.Add(item);
返回Json(item,JsonRequestBehavior.AllowGet);
}
public JsonResult UpdateProduct(int id,TblProductList product)
{
product.Id = id;
if(repository.Update(product))
返回Json(repository.GetAll(),JsonRequestBehavior.AllowGet);
返回Json(null);
}
public JsonResult DeleteProduct(int id)
{
if(repository.Delete(id))
返回Json(new {Status = true},JsonRequestBehavior.AllowGet);
返回Json(new {Status = true},JsonRequestBehavior.AllowGet);
}
}
}
--------------- -------------------------------------
Interface类中的编码是
------------------------------------
使用System;
使用System.Collections.Generic;
使用System.Linq;
使用System.Web;
使用MvcWithKnockoutJS.Models;
名称空间MvcWithKnockoutJS.Interfaces
{
interface IProductRepository
{
IEnumerable< tblproductlist> GetAll();
TblProductList Get(int id);
TblProductList Add(TblProductList item);
bool Update(TblProductList item);
bool删除(int id);
}
}
- -------------------------------------------------- -------------
接口成员实现类中的编码
--------------- -----------------------------
使用System;
使用System .Collections.Generic;
使用System.Linq;
使用System.Web;
使用MvcWithKnockoutJS.Interfaces;
使用MvcWithKnockoutJS.Models;
名称空间MvcWithKnockoutJS.Repositories
{
公共类ProductRepository:IProductRepository
{
MvcWithKnockoutJSEntities connectDB = new MvcWithKnockoutJSEntities();
//实现接口成员以获取所有记录来自数据库的ds。
public IEnumerable< tblproductlist> GetAll()
{
//待办:获取数据库中所有记录列表的代码
返回connectDB.TblProductLists;
}
//通过Id从数据库获取记录的接口成员的实现
public TblProductList Get(int id)
{
//待办事项:在数据库中查找记录的代码
返回connectDB.TblProductLists.Find(id);
}
//接口成员插入数据的实现
public TblProductList Add(TblProductList item)
{
if (item == null)
{
抛出新的ArgumentNullException(item);
}
/ /待办事项:将记录保存到数据库的代码
connectDB.TblProductLists.Add(item);
connectDB.SaveCh anges();
返回项目;
}
//实现接口成员将数据更新到数据库
public bool Update(TblProductList item)
{
if(item == null)
抛出新的ArgumentNullException(item);
// TO DO:将记录更新到数据库的代码
var products = connectDB.TblProductLists.Single(a => a.Id == item.Id);
products.Name = item.Name;
products.Category = item.Category;
products.Price = item.Price;
connectDB.SaveChanges();
返回true;
}
//从数据库中删除数据的接口成员的实现
public bool删除(int id)
{
// TO DO:Code to从数据库中删除记录
TblProductList deleteItems = connectDB.TblProductLists.Find(id);
connectDB.TblProductLists.Remove(deleteItems);
返回true;
}
}
}
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;
}
}
}
推荐答案
.ajax( {
url:'Product / GetAllProducts',
cache:false,
类型:'GET',
contentType:'application / json; charset = u tf-8',
数据:{},
成功:函数(数据){
self.Products(data); //将响应放入ObervableArray
}
});
//初始化后计算总价
self.Total = ko.computed(function(){
var sum = 0;
var arr = self.Products();
for(var i = 0; i< arr.length; i ++){
sum + = arr [i] .Price;
}
返还金额;
});
//添加新商品
self.create = function(){
if(Product.Name()!=&& Product.Price()!=&&& Product.Category ()!=){
.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,
类型:'POST',
contentType:'application / json; charset = utf-8',
data :ko.toJSON(产品),
成功:功能(数据){
self.Products.push(数据);
self.Name();
self。价格();
self.Category();
alert('产品已成功添加!');
}
})。失败(
函数(xhr,textStatus,错误){
alert(错误);
});
}
else {
alert('EMPLY FIELDS不允许'------- -------------------------------------------------- ----- \ n请输入所有值。\ n所有字段都是必填项。');
}
}
< br $>
//删除产品详细信息
self.delete = function(产品){
if(确认('你确定要删除''+ Product.Name +'product ??')) {
var id = Product.Id;
.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,
类型:'POST',
contentType:'application / JSON; charset = utf-8',
数据:id,
成功:函数(数据){
self.Products.remove(Product) ;
alert('产品已被删除!');
}
})。失败(
function(xhr,textStatus,err){
self.status(err);
});
}
}
//编辑产品详情
self.edit = function(产品){
self .Product(产品);
}
//更新产品详情
self.update = function( ){
var Product = self.Product();
var id = Product.Id;
console.log(id);
if(Product.Name!=& Product.Price!=& Product.Category!=){
.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 != "") {
这篇关于可选参数必须是引用类型,可空类型,或者声明为可选参数。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!