Lỗi session: Object reference not set to an instance of an object
Hiện em đang làm website bán rượu bằng asp.net mvc, đến phần giỏ hàng thì em làm theo clip: https://www.youtube.com/watch?v=ZBd0MnKb7u0
Import database vào và tạo pj mới thì không có lỗi, nhưng khi điền vào trong code thì trong IndexCart, chỗ session bị lỗi: ‘Object reference not set to an instance of an object.’
Trang IndexCart
@model IEnumerable<CT241Ancol.Models.ancohol>
@{
ViewBag.Title = "IndexCart";
Layout = "~/Views/Shared/_UserPage.cshtml";
}
@using CT241Ancol.Models
<h2>IndexCart</h2>
<h2>Cart</h2>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title> Card </title>
</head>
<body>
<table cellpadding="2" cellspacing="2" border="1">
<tr>
<th> Option </th>
<th> ancohol_code </th>
<th> ancohol_name </th>
<th> ancohol_price </th>
<th> Quantity </th>
<th> Sub Total </th>
</tr>
@foreach (var item in (List<Item>)Session["cart"])
{
<tr>
<td> @Html.ActionLink("Delete", "Delete", "ShoppingCart", new { id = item.Wine.ancohol_id }, null) </td>
<td> @item.Wine.ancohol_code </td>
<td> @item.Wine.ancohol_name </td>
<td> @item.Wine.ancohol_price </td>
<td> @item.Wine.ancohol_number </td>
<td> @(item.Wine.ancohol_price * item.Wine.ancohol_number) </td>
</tr>
}
<tr>
<td colspan="5">Sum</td>
</tr>
</table>
<br /><br />
@*@Html.ActionLink("Continue Shopping", "Index", "ancoholIndex1")*@
</body>
</html>
ShoppingCartController
using System.Collections.Generic;
using System.Web.Mvc;
using CT241Ancol.Models;
namespace CT241Ancol.Controllers
{
public class ShoppingCartController : Controller
{
private CT241_AncoholEntities context = new CT241_AncoholEntities();
public ActionResult IndexShoppingCart()
{
return View();
}
public ActionResult IndexCart()
{
return View();
}
private int isExisting(int? id)
{
List<Item> cart = (List<Item>)Session["cart"];
for (int i = 0; i < cart.Count; i++)
if (cart[i].Wine.ancohol_id == id)
return i;
return -1;
}
public ActionResult Delete(int id)
{
int index = isExisting(id);
List<Item> cart = (List<Item>)Session["cart"];
cart.RemoveAt(index);
Session["cart"] = cart;
return View("Cart");
}
public ActionResult OrderNow(int? id)
{
if (Session["cart"] == null)
{
List<Item> cart = new List<Item>();
cart.Add(new Item(context.ancohols.Find(id), 1));
Session["cart"] = cart;
}
else
{
List<Item> cart = (List<Item>)Session["cart"];
int index = isExisting(id);
if (index == -1) // Item is not existed
cart.Add(new Item(context.ancohols.Find(id), 1));
else
cart[index].Wine.ancohol_number++;
Session["cart"] = cart;
}
return View("Cart");
}
}
}
Model Item
namespace CT241Ancol.Models
{
public class Item
{
private ancohol wine = new ancohol();
private int quantity;
public Item()
{
}
public Item(ancohol wine, int quantity)
{
this.Wine = wine;
this.Quantity = quantity;
}
public int Quantity
{
get { return quantity; }
set { quantity = value; }
}
public ancohol Wine
{
get { return wine; }
set { wine = value; }
}
}
}
ancoholController (lúc đặt tên bạn e nó đặt nhầm
using System.Linq;
using System.Web.Mvc;
using System.Net;
using CT241Ancol.Models;
using System.IO;
namespace CT241Ancol.Controllers
{
public class ancoholController : Controller
{
// GET: ancohol
private CT241_AncoholEntities context = new CT241_AncoholEntities();
public ActionResult ancoholIndex1()
{
ViewBag.listAlco = context.ancohols.ToList();
return View();
}
[HttpGet]
public ActionResult ancoholIndex()
{
var listAnchol = DataHelper.getAncoholList();
return View(listAnchol);
}
[HttpGet]
public ActionResult ancoholCreate()
{
ViewData["Departments"] = new SelectList(context.ancohols, "ancohol_id", "ancohol_code");
var lst = DataHelper.getcategorylist1();
ViewData["cat_id"] = new SelectList(lst, "cat_id", "cat_name");
ViewData["cat_name"] = new SelectList(lst, "cat_name");
var lst1 = DataHelper.getpublisher1();
ViewData["pd_id"] = new SelectList(lst1, "pd_id", "pd_name");
ViewData["pd_name"] = new SelectList(lst1, "pd_name");
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult ancoholCreate([Bind(Include = "ancohol_id,ancohol_code,ancohol_name,ancohol_price,ancohol_description,ancohol_view,ancohol_number,ancohol_image,ancohol_rate,ancohol_rate_num,cat_id,pd_id")] ancohol Wine)
{
//Test
if (!ModelState.IsValid)
{
return View(Wine);
}
ViewData["Departments"] = new SelectList(context.ancohols, "ancohol_id", "ancohol_code");
var lst = DataHelper.getcategorylist1();
ViewData["cat_id"] = new SelectList(lst, "cat_id", "cat_name");
ViewData["cat_name"] = new SelectList(lst, "cat_name");
var lst1 = DataHelper.getpublisher1();
ViewData["pd_id"] = new SelectList(lst1, "pd_id", "pd_name");
ViewData["pd_name"] = new SelectList(lst1, "pd_name");
using (CT241_AncoholEntities context = new CT241_AncoholEntities())
{
//Lấy các file upload vào CSDL
for (int i = 0; i < Request.Files.Count; i++)
{
var File = Request.Files[i];
if (File != null && File.ContentLength > 0)
{
if (File.ContentLength > 0)
{
string _FileName = Path.GetFileName(File.FileName);
string _path = Path.Combine(Server.MapPath("~/UploadFiles"), _FileName);
File.SaveAs(_path);
Wine.ancohol_image = _FileName;
}
}
}
context.ancohols.Add(Wine);
context.SaveChanges();
return RedirectToAction("ancoholIndex");
}
}
[HttpGet]
public ActionResult ancoholEdit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
ViewData["Departments"] = new SelectList(context.ancohols, "ancohol_id", "ancohol_code");
var lst = DataHelper.getcategorylist1();
ViewData["cat_id"] = new SelectList(lst, "cat_id", "cat_name");
ViewData["cat_name"] = new SelectList(lst, "cat_name");
var lst1 = DataHelper.getpublisher1();
ViewData["pd_id"] = new SelectList(lst1, "pd_id", "pd_name");
ViewData["pd_name"] = new SelectList(lst1, "pd_name");
var obj = DataHelper.getAncoholId(id);
return View(obj);
}
[HttpPost]
public ActionResult ancoholEdit(ancohol obj)
{
if (!ModelState.IsValid)
{
ModelState.AddModelError("", "Error in saving data");
return View();
}
DataHelper.editAncohol(obj);
return View("~/Views/Home/Index.cshtml", obj);
}
[HttpGet]
public ActionResult ancoholDelete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var obj = DataHelper.getAncoholId(id);
return View(obj);
}
[HttpPost, ActionName("ancoholDelete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int? id)
{
var obj = DataHelper.getAncoholId(id);
if (obj != null)
{
DataHelper.deleteAncohol(obj);
}
return RedirectToAction("ancoholIndex");
}
}
}
Còn đây là code trong clip em làm theo
AlcoController
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SakayanagiArisu.Models;
namespace SakayanagiArisu.Controllers
{
public class AlcoController : Controller
{
private ArisuEntities arisu = new ArisuEntities();
public ActionResult Index()
{
ViewBag.listAlco = arisu.ancohols.ToList();
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
}
}
Item
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using SakayanagiArisu.Models;
namespace SakayanagiArisu.Controllers
{
public class Item
{
private ancohol alcohol = new ancohol();
private int quantity;
public Item()
{
}
public Item(ancohol alcohol, int quantity)
{
this.Alcohol = alcohol;
this.Quantity = quantity;
}
public ancohol Alcohol { get => alcohol; set => alcohol = value; }
public int Quantity { get => quantity; set => quantity = value; } // Ctrl + r ctrl + e
}
}
ShoppingCartController
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SakayanagiArisu.Models;
namespace SakayanagiArisu.Controllers
{
public class ShoppingCartController : Controller
{
private ArisuEntities arisu = new ArisuEntities();
// GET: ShoppingCart
public ActionResult Index()
{
return View();
}
private int isExisting(int? id)
{
List<Item> cart = (List<Item>)Session["cart"];
for (int i = 0; i < cart.Count; i++)
if (cart[i].Alcohol.ancohol_id == id)
return i;
return -1;
}
public ActionResult Delete(int id)
{
int index = isExisting(id);
List<Item> cart = (List<Item>)Session["cart"];
cart.RemoveAt(index);
Session["cart"] = cart;
return View("Cart");
}
public ActionResult OrderNow(int? id)
{
if (Session["cart"] == null)
{
List<Item> cart = new List<Item>();
cart.Add(new Item(arisu.ancohols.Find(id), 1));
Session["cart"] = cart;
}
else
{
List<Item> cart = (List<Item>)Session["cart"];
int index = isExisting(id);
if (index == -1) // Item is not existed
cart.Add(new Item(arisu.ancohols.Find(id), 1));
else
cart[index].Alcohol.ancohol_number++;
Session["cart"] = cart;
}
return View("Cart");
}
}
}
IndexCartView
@{
Layout = null;
}
@using SakayanagiArisu.Controllers
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title> Card </title>
</head>
<body>
<table cellpadding="2" cellspacing="2" border="1">
<tr>
<th> Option </th>
<th> ancohol_code </th>
<th> ancohol_name </th>
<th> ancohol_price </th>
<th> Quantity </th>
<th> Sub Total </th>
</tr>
@*double total = 0;*@
@foreach (var item in (List<Item>)Session["cart"])
{
//total += Convert.ToDouble(item.Alcohol.ancohol_price * item.Alcohol.ancohol_number);
<tr>
<td> @Html.ActionLink("Delete", "Delete", "ShoppingCart", new { id = item.Alcohol.ancohol_id}, null) </td>
<td> @item.Alcohol.ancohol_code </td>
<td> @item.Alcohol.ancohol_name </td>
<td> @item.Alcohol.ancohol_price </td>
<td> @item.Alcohol.ancohol_number </td>
<td> @(item.Alcohol.ancohol_price * item.Alcohol.ancohol_number) </td>
</tr>
}
<tr>
<td colspan="5">Sum</td>
@*<td> @total </td>*@
</tr>
</table>
<br/><br/>
@Html.ActionLink("Continue Shopping", "Index", "Alco")
</body>
</html>