【发布时间】:2020-12-27 13:37:21
【问题描述】:
我正在使用 ASP.NET Core MVC 对我自己的网站进行编程,并按照我想要迭代从我的数据库填充到视图的数据的视频教程之一。以下是代码:
存储库
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();
}
}
控制器:
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);
}
}
索引.cshtml
@page
@model IEnumerable<ChoreBear_Website.Models.CategoryofTask>
<div class="row">
@foreach (var category in Model)
{
<partial name="Categories" model=@Model/>
}
</div>
部分视图(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>
该列表包含来自数据库的数据,但网站项目向我返回了一个错误:
NullReferenceException:对象引用未设置为 目的。 MyApp.Namespace.Home.Views_Home_Index.get_Model()
我知道列表是空的,这就是为什么我想知道我应该在哪里初始化列表。我按照视频教程中的代码示例进行操作。
PS:我从数据库中关注了这个视频教程Get List of Data
【问题讨论】:
-
你试过调试吗? (一步一步)这将有助于轻松找到这种错误(如果不涉及多线程)。
-
@Hopeless 您好,由于我使用的是 VS Code,因此无法逐步调试。有什么办法吗?谢谢
标签: c# asp.net-core entity-framework-core asp.net-core-mvc