2

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

2
  • have you tried debugging it? (step by step) that would help find this kind of bug easily (in case multithreading is not involved). Commented Dec 27, 2020 at 13:42
  • @Hopeless Hi, I can't debugging step by step since I'm using VS Code. Is there any way to do it? Thanks Commented Dec 27, 2020 at 13:52

1 Answer 1

2

Your code looks OK to retrieve a list and return it to a VIEW "Index", even if that list is empty because there are no records in the database.

However, there are two problems. One your Index.cshtml has the "@page" directive which means it is now a Razor Page instead of a View and expects to find the model in the page behind Index.cshtml.cs or in a @code section on the same page. This is the source of your error.

Additionally, in the following, your are passing the IEnumerable as the model to the partial view, which is expecting an individual CategoryOfTask ...

@model IEnumerable<ChoreBear_Website.Models.CategoryofTask>

<div class="row">
    @foreach (var category in Model)
    {
        <partial name="Categories" model=@Model/>
    }
</div>

Try changing ...

<partial name="Categories" model=@Model/>

to ...

<partial name="Categories" model=@category/>

To understand differences between Razor Views and Pages, see this link:

https://learn.microsoft.com/en-us/aspnet/core/razor-pages/?view=aspnetcore-5.0&tabs=visual-studio

The preceding code looks a lot like a Razor view file used in an ASP.NET Core app with controllers and views. What makes it different is the @page directive. @page makes the file into an MVC action - which means that it handles requests directly, without going through a controller. @page must be the first Razor directive on a page. @page affects the behavior of other Razor constructs. Razor Pages file names have a .cshtml suffix.

Sign up to request clarification or add additional context in comments.

4 Comments

Hi @Neil W, did what you have suggested. It didn't solve the issue. Got an error which is at "@foreach (var category in Model)".
Try removing that "@page" from the first line of Index.cshtml.
Have edited the answer with a fuller description.
I removed it and it worked. Thanks for the link as well. Now, I know why the @page directive does

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.