Переданный элемент модели не соответствует ожидаемому IEnumerable - PullRequest
0 голосов
/ 21 апреля 2020

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

Я видел другие исправления этой проблемы, но не могу заставить ее работать.

Вот мой оригинальный метод индекса.

    // GET: Reservations
    public ActionResult Index()
    {
        var reservations = db.Reservations.Include(r => r.Bike).Include(r => r.Customer).Include(r => r.DropoffStore).Include(r => r.PickupStore);
        return View(reservations.ToList());
    }

Вот мой новый метод индекса контроллера, который я получил от кого-то другого, но я не знаю, почему я не буду работать:

    // GET: Reservations
    public ActionResult Index()
    {
        var reservations = db.Reservations.Include(r => r.Bike).Include(r => r.Customer).Include(r => r.DropoffStore).Include(r => r.PickupStore);

        IEnumerable<ReservationViewModel> reservationViewModels = new List<ReservationViewModel>();

        foreach (var reservation in reservations)
        {
            var reservationViewModel = new ReservationViewModel
            {

            };

            reservationViewModels.ToList().Add(reservationViewModel);

        }

        return View(reservationViewModels);
    }

Вот моя страница индекса:

@model IEnumerable<ASP.NET_Framwork_for_real_bitch.ViewModels.ReservationViewModel>

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Reservation.Customer.FirstName)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Reservation.Customer.LastName)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Reservation.Customer.Email)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Reservation.Customer.Gender)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Reservation.DropoffStore_Id)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Reservation.PickupStore_Id)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Reservation.StartDate)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Reservation.EndDate)
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
<tr>
    <td>
        @Html.DisplayFor(modelItem => item.Reservation.Customer.FirstName)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.Reservation.Customer.LastName)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.Reservation.Customer.Email)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.Reservation.Customer.Gender)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.Reservation.DropoffStore.StoreName)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.Reservation.PickupStore.StoreName)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.Reservation.StartDate)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.Reservation.EndDate)
    </td>
    <td>
        @Html.ActionLink("Edit", "Edit", new { id = item.Reservation.Id }) |
        @Html.ActionLink("Delete", "Delete", new { id = item.Reservation.Id })
    </td>
</tr>
}

</table>

Это точная ошибка:

The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[ASP.NET_Framwork_for_real_bitch.Models.Reservation]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[ASP.NET_Framwork_for_real_bitch.ViewModels.ReservationViewModel]'.

Модель полного бронирования ViewView:

using ASP.NET_Framwork_for_real_bitch.Models;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace ASP.NET_Framwork_for_real_bitch.ViewModels
{
    public class ReservationViewModel
    {
        private BikeShoppaModel db = new BikeShoppaModel();
        public Reservation Reservation { get; set; }
        public SelectList DropoffStore_Id { get; private set; }
        public SelectList PickupStore_Id { get; private set; }
        public SelectList Bikes { get; private set; }
        public SelectList CustomerGender { get; set; }
        public int TotalDays { get; set; }
        public double TotalPrice { get; set; }
        public ReservationViewModel()
        {
            DropoffStore_Id = new SelectList(db.Stores, "Id", "StoreName");
            PickupStore_Id = new SelectList(db.Stores, "Id", "StoreName");
            Bikes = new SelectList(db.Bikes, "Id", "Brand");
            CustomerGender = new SelectList(db.Customers, "Id", "Gender");
        }
        public ReservationViewModel(int id) : this()
        {
            Reservation = db.Reservations.Find(id);
            TotalDays = (Reservation.EndDate.Date - Reservation.StartDate.Date).Days + 1;
        }

        public void Save()
        {
            if(Reservation.Id > 0)
            {
                db.Entry(Reservation).State = EntityState.Modified;
            }
            else
            {
                db.Reservations.Add(Reservation);
            }



            db.SaveChanges();
        }   
    }
}

Модель моего бронирования:

public class Reservation
    {
        public int Id { get; set; }

        [ForeignKey("Customer")]
        [Display(Name = "Customer")]
        public int Customer_Id { get; set; }
        public virtual Customer Customer { get; set; }
        [ForeignKey("Bike")]
        public int Bike_Id { get; set; }
        public Bike Bike { get; set; }


        [DataType(DataType.Date)]
        [Column(TypeName = "Date")]
        [Display(Name = "Start date")]
        public DateTime StartDate { get; set; }

        [DataType(DataType.Date)]
        [Column(TypeName = "Date")]
        [Display(Name = "End date")]
        public DateTime EndDate { get; set; }

        [ForeignKey("PickupStore")]
        [Display(Name = "Pickup store")]
        public int PickupStore_Id { get; set; }
        public Store PickupStore { get; set; }

        [ForeignKey("DropoffStore")]
        [Display(Name = "Dropoff store")]
        public int DropoffStore_Id { get; set; }
        public Store DropoffStore { get; set; }
    }

Ответы [ 2 ]

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

Пожалуйста, замените метод действия Controller Index на приведенный ниже и оставьте свои комментарии:

// GET: Reservations
public ActionResult Index()
{
    var reservations = db.Reservations.Include(r => r.Bike).Include(r => r.Customer).Include(r => r.DropoffStore).Include(r => r.PickupStore);

    var reservationViewModels = new List<ReservationViewModel>();

    foreach (var reservation in reservations)
    {
        var reservationViewModel = new ReservationViewModel
        {

        };

        reservationViewModels.Add(reservationViewModel);
    }
    /* 
      // In short you can populate your viewmodels and return as below:
      return (reservations.Select(r => new ReservationViewModel{
      }).AsEnumerable());
    */

    return View(reservationViewModels.AsEnumerable());
}

Только примечание: вы в основном перепутали модель сущностей и модель представления. Требуется много очистки и / или рефакторинга.

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

Вы возвращаете список бронирований в методе индекса вашего контроллера. Ваше представление ожидает IEnumerable из ReservationViewModels. Таким образом, ваш Контроллер производит яблоки, но вашему виду нужны апельсины. Таким образом, вам нужно преобразовать яблоки в апельсины, чтобы это работало - одно из нескольких преимуществ, которые дает разработчик программного обеспечения, чтобы это сделать :-) Попробуйте что-то вроде этого: яблоки (объекты типа Reservation) и производят апельсин (объект типа ReservationViewModel) для каждого яблока. В конце вы передаете этот набор апельсинов (IEnuerable of ReservationViewModel = на ваш взгляд и все готово.

...