Reputation: 103
I want to Display each element on Razor view from Model through foreach loop,I have no code in Controller when I run the Application , I get the Error:
Object reference not set to Instance of an Object
Please some body help me, I wrote the code in the View
@model IEnumerable<Models.Web.Category>
@foreach(var item in Model){
@item.CategoryName
}
and My Controller is
public ActionResult Category(){
return View();
}
Upvotes: 0
Views: 2010
Reputation: 15138
Look your view is expecing a Model
:
@model IEnumerable<Models.Web.Category>
In your Controller you're not passing anything to the view, so the view has null
as a Model.
You need to create your collection IEnumerable<Category>
and pass it to the view.
Upvotes: 0
Reputation: 15866
I mean something like this:
public ActionResult Category(){
var categories = db.Categories;
return View(categories);
}
OR
public ActionResult Category(){
List<Category> categories = new List<Category>();
categories.Add(new Category() { ID = 1, Name = "Bikes" });
categories.Add(new Category() { ID = 2, Name = "Cars" });
categories.Add(new Category() { ID = 3, Name = "Trucks" });
return View(categories);
}
You should initialize your model in controller...
Upvotes: 1
Reputation: 887225
Model
is null.
If you want to display data from the model, you need to pass a model from the controller.
Upvotes: 0