I am view specific category of item in a view. I want it to view all products under that category when clicked but I get a null reference exception. I have seperate tables for the category and products.
Here is what I tried. Code in view:
@model IEnumerable<OpabidFarmsLtd.Models.ViewModels.Shop.CategoryVM>
<h3>Categories</h3>
<ul>
<li><a href="#">All</a></li>
@foreach (var item in Model)
{
<li><a href="/shop/category/@item.Slug.ToLower()">@item.Name</a></li>
}
</ul>
And my controller (ShopController):
public ActionResult Category(string name)
{
// Declare a list of ProductVM
List<ProductVM> productVMList;
using (Db db = new Db())
{
// Get category id
CategoryDTO categoryDTO = db.Categories.Where(x => x.Slug == name).FirstOrDefault();
int catId = categoryDTO.Id;
// Init the list
productVMList = db.Procucts.ToArray().Where(x => x.CategoryId == catId).Select(x => new ProductVM(x))
.ToList();
// Get category name
var productCat = db.Procucts.Where(x => x.CategoryId == catId).FirstOrDefault();
ViewBag.CategoryName = productCat.CategoryName;
}
// Return view with list
return View(productVMList);
}
Edit: While looking for what is wrong, I discovered that the method Category never got the parameter at all, I commented all the codes in it and did this:
public ActionResult Category(string name)
{
string cat;
using (Db db = new Db())
{
CategoryDTO dto = db.Categories.Where(x => x.Slug == "test-category").FirstOrDefault();
cat = dto.Id.ToString();
}
return Content(name + cat);
}
It returned only 8 which was the Id from the database. I know why it was giving me null, it was because it never received any parameter then default to null. What I can't figure out now is why the parameter isn't getting there from my code above. Please help, I am new to this framework.
db.Categories.Where(x => x.Slug == name)there mustn't be anyCategoryDTO's that satisfy that condition.categoryDTOvariable ends withFirstOrDefault. The query didn't find any results, so it assigned the variable the default value for that type (anull). When you try to access a property of a null object you get that exception.namein the Slug column?