Reputation: 426
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.
Upvotes: 1
Views: 337
Reputation: 76
You try to send "productVMList" to view but you add categoryVM model to html page. I think you should send "categoryVMList" instead of "productVMList" or you should add productVM to your view. Like;
@model IEnumerable<OpabidFarmsLtd.Models.ViewModels.Shop.ProductVM>
Also you should use .Add to add new item to the list. For example,
ProductVMList.Add(object)
Otherwise, put breakpoint to return View(ProductVMList)
and check list null or filled.
Upvotes: 2