I was programming my own website using ASP.NET Core MVC and following one of the video tutorials I wanted to iterate data which is populated from my database to the view. Here are the codes:
Repository
public class ChoreBearRepository : IChoreBearRepo
{
private readonly DatabaseContext _context;
public ChoreBearRepository(DatabaseContext context)
{
_context = context;
}
/*
This methods returns all categories from the database using the background thread.
*/
public async Task<List<CategoryofTask>> GetAllCategories()
{
return await _context.categoryOfTasks
.Select(category => new CategoryofTask(){
CategoryName = category.CategoryName,
CategoryDesc = category.CategoryDesc,
CategoryID = category.CategoryID,
CategoryImageURL = category.CategoryImageURL,
CategoryRate = category.CategoryRate
}).ToListAsync();
}
}
Controller:
public class HomeController: Controller
{
private readonly IChoreBearRepo _repository;
public HomeController(IChoreBearRepo repository)
{
_repository = repository;
}
// public IActionResult Index()
// {
// return View();
// }
[HttpGet]
public async Task<IActionResult> Index()
{
var data = await _repository.GetAllCategories();
return View(data);
}
}
Index.cshtml
@page
@model IEnumerable<ChoreBear_Website.Models.CategoryofTask>
<div class="row">
@foreach (var category in Model)
{
<partial name="Categories" model=@Model/>
}
</div>
Partial View (Categories.cshtml)
@model CategoryofTask
<div class="card" style="width: 18rem;">
<img class="card-img-top" src="@Model.CategoryImageURL" alt="Card image cap">
<div class="card-body">
<h5 class="card-title">@Model.CategoryName</h5>
<p class="card-text">@Model.CategoryDesc</p>
<a href="#" class="btn btn-primary">Go somewhere</a>
</div>
</div>
The list contains data from the database but the website project returns me an error which is :
NullReferenceException: Object reference not set to an instance of an object. MyApp.Namespace.Home.Views_Home_Index.get_Model()
I do know that the list is null which is why I would like to know where should I initialise the list. I followed the code example from the video tutorial.
PS: I followed this video tutorial Get List of Data from Database