我正試圖在我的表格上顯示每輛汽車的影像。當我運行代碼時,View崩潰了,我得到的錯誤是
。物件參考沒有設定為一個物件的實體我在資料庫中保存了圖片,它們與汽車相關聯,所以我不確定為什么我得到了空值。
這是我的觀點
@model IEnumerable< IgnitionHub2._0.Models.Car> <table class="table"/span>> <tr> <th> @Html.DisplayNameFor(model => model.ImageList.Title) </th> <th> @Html.DisplayNameFor(model => model.CarID) </th> <th> @Html.DisplayNameFor(model => model.MarketValue) </th> <th> @Html.DisplayNameFor(model => model.Year) </th> <th> @Html.DisplayNameFor(model => model.Model.Make.Name) </th> <th> @Html.DisplayNameFor(model => model.Model.Name) </th> <th></th> </tr> @foreach (var item in Model) { <tr> <td> <img [email protected]("/CarImages/{0}", item.Images.FirstOrDefault().Title) /> </td> <td> @Html.DisplayFor(modelItem => item.CarID) </td> <td> @Html.DisplayFor(modelItem => item.MarketValue) </td> <td> @Html.DisplayFor(modelItem => item.Year) </td> <td> @Html.DisplayFor(modelItem => item.Model.Make.Name) </td> <td> @Html.DisplayFor(modelItem => item.Model.Name) </td> <td> @Html.ActionLink("Edit", "Edit", new { id = item.CarID }) | @Html.ActionLink("詳細資訊", "詳細資訊", new { id = item.CarID }) | @Html.ActionLink("洗掉", "洗掉", new { id = item.CarID }) </td> </tr> } </table>這就是控制器
public ActionResult _Index() { var cars = new List<Car>(db.Cars)。 return PartialView(cars); }這些是模型:
namespace IgnitionHub2._0.Models { 使用System.ComponentModel.DataAnnotations。 使用System.Linq.DataAnnotations using System.Collections.Generic; using System.ComponentModel; public partial class Car { public Car() { } public int CarID { get; set; } public string Year { get; set; } public string Color { get; set; } public string Mileage { get; set; } public string BodyType { get; set; } public string Drive { get; set; } public string Notes { get; set; } public bool Available { get; set; } public string VinNumber { get; set; } public int CarLotID { get; set; } public int ModelID { get; set; } public virtual Model模型 { get; set; } public virtual ICollection<Image> Images { get; set; } public HttpPostedFileBase[] files { get; set; } public IEnumerable<Car> SelectedCar { get; set; } public virtualImage ImageList { get; set; } }這就是影像的模型
namespace IgnitionHub2._0.Models { 使用系統。 using System.Collections.Generic; using System.ComponentModel; public partial class Image { public int ImageID { get; set; } public int CarID { get; set; } public string Title { get; set; } public string ImagePath { get; set; } public virtual Car 汽車 { get; set; } public HttpPostedFileBase[] files { get; set; } }我的應用程式在到達視圖中的
@foreach (var item in Model)時崩潰了。請幫助! 謝謝你的幫助。
uj5u.com熱心網友回復:
我能夠通過改變代碼來使我的代碼作業
<td> <img [email protected]("/CarImages/{0}",item.Images.FirstOrDefault().Title) /> </td>到。
<td> @if (item.Images.Count > 0) {<img [email protected]("/CarImages/{0}", item.Images.FirstOrDefault().Title) /> } </td>轉載請註明出處,本文鏈接:https://www.uj5u.com/net/320365.html
標籤:
