所以我正在尝试访问页面 localhost/Catalog/Detail/{id},但是当我尝试访问例如 localhost/Catalog/Detail/1 时,Visual Studio 告诉我我的 id = 0 发生这种情况的任何原因?下面是视图的控制器。
public IActionResult Detail(int id)
{
var asset = _assets.GetById(id);
var model = new AssetDetailModel
{
AssetId = id,
Title = asset.Title,
Year = asset.Year,
Cost = asset.Cost,
Status = asset.Status.Name,
ImageUrl = asset.ImageUrl,
AuthorOrDirector = _assets.GetAuthorOrDirector(id),
CurrentLocation = _assets.GetCurrentLocation(id).Name,
DeweyCallNumber = _assets.GetDeweyIndex(id),
ISBN = _assets.GetIsbn(id)
};
return View(model);
}
我得到的错误如下(由于我使用 FirstOrDefault 来检索它,但正如 Visual Studio 所示,它接收的 int id 值是 id = 0,所以它会给我默认值,即无效的)
System.NullReferenceException: 'Object reference not set to an instance of an object.'
asset was null.
以防万一有人问我的路由模板是
"{controller=Home}/{action=Index}/{id?}");
更新 1:我检查了代码源,发现我的视图正在检索正确的 @Model.ImageUrl 并将给我一个正确的值,如下所示(如果 id = 1,它将检索 emma.png)但图片不会被加载/Catalog/Detail/1,但会加载到 /Catalog 并且 VS 会触发我上面提到的错误
<div>
<img src="detailImage" alt="/images/emma.png" />
</div>