Question: Getting this error -- ASP.NET/Razor NullReferenceException: Object reference not set to an instance of an object. Line 21: @{ Line 22: Line 23: foreach (Product

Getting this error -- ASP.NET/Razor

NullReferenceException: Object reference not set to an instance of an object. 

Line 21: @{ Line 22: Line 23: foreach (Product p in ViewBag.Product) Line 24: { Line 25:  

Could someone please help me understand what I'm doing wrong? I've posted code for two pages:

DisplayProducts.cshtml

HomeController.cs

********CODE*********

DisplayProducts.cshtml

@using HTMLHelpers.Models

@{

ViewBag.Title = "DisplayProducts";

}

DisplayProducts

@foreach (Product p in ViewBag.Product)

{

}

Name Price ($) Quantity Total ($)
@p.Name @p.Price 0.00
Total 0.00

@section Scripts {

}

HomeController.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

using HTMLHelpers.Models;

namespace Unit2.Controllers

{

public class HomeController : Controller

{

public ActionResult Index()

{

return View();

}

public ActionResult About()

{

ViewBag.Message = "Your application description page.";

return View();

}

public ActionResult Contact()

{

ViewBag.Message = "Your contact page.";

return View();

}

public ActionResult DisplayProducts()

{

Product p = new Product();

ViewBag.products = p.Get();

return View(new );

}

[HttpPost]

public ActionResult ProcessOrder(FormCollection form)

{

List Orders = new List();

Product prod = new Product();

foreach (var p in prod.Get())

{

int qty = Convert.ToInt16(form[p.Id]);

if (qty > 0)

{

Orders.Add(new Order { Prod = p, Qty = qty });

}

}

ViewBag.Orders = Orders;

return View();

}

}

}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!