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
@section Scripts {
$(function (e) {
$('.qty').change(function (e) {
var qty = $('#' + this.id).val();
var price = $('#price_' + this.id).html();
$('#total_' + this.id).html((qty * price).toFixed(2));
var total = 0;
$('.qty').each(function (e) {
total += Number($('#total_' + this.id).html());
});
$('#total').html(total.toFixed(2));
});
});
}
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
Question Has Been Solved by an Expert!
Get step-by-step solutions from verified subject matter experts
Step: 2 Unlock
Step: 3 Unlock
