Почему я не могу заполнить свои изображения в моих таблицах в моем приложении ASP. NET MVC? - PullRequest
0 голосов
/ 21 апреля 2020

Я пытаюсь отобразить изображение для каждой машины на моем столе. Когда я запускаю код, представление падает, и я получаю ошибку

Ссылка на объект не установлена ​​на экземпляр объекта

У меня есть изображения, сохраненные в моей базе данных, и они связаны с автомобилем, поэтому я не уверен, почему я получаю нулевое значение.

Это мой взгляд

@model IEnumerable<IgnitionHub2._0.Models.Car>

<table class="table">
    <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 src=@String.Format("/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("Details", "Details", new { id = item.CarID }) |
        @Html.ActionLink("Delete", "Delete", new { id = item.CarID })
    </td>
    </tr>
    }
</table>

Это контроллер

public ActionResult _Index()
{
    var cars = new List<Car>(db.Cars); 
    return PartialView(cars);
}

Это модели:

namespace IgnitionHub2._0.Models
{
    using System.ComponentModel.DataAnnotations;
    using System.Linq;
    using System;
    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 Model { get; set; }
            public virtual ICollection<Image> Images { get; set; }
            public HttpPostedFileBase[] files { get; set; }
            public IEnumerable<Car> SelectedCar { get; set; }
            public virtual Image ImageList { get; set; }
    }
}

Это модель для Image

namespace IgnitionHub2._0.Models
{
    using System;
    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 Car { get; set; }
        public HttpPostedFileBase[] files { get; set; }
    }
}

Мое приложение падает, когда оно достигает @foreach (var item in Model) в представлении.

Пожалуйста, помогите! Заранее спасибо.

1 Ответ

0 голосов
/ 22 апреля 2020

Я смог заставить свой код работать, изменив

<td>
    <img src=@String.Format("/CarImages/{0}",item.Images.FirstOrDefault().Title) />
</td>

на:

<td>
    @if (item.Images.Count > 0)
    {<img src=@String.Format("/CarImages/{0}", item.Images.FirstOrDefault().Title) />}
</td>
...