使用 ViewModel 时在 Razor 中的运行时崩溃

本文关键字:运行时 崩溃 Razor ViewModel 时在 使用 | 更新日期: 2023-09-27 17:56:36

我正在尝试通过ViewModel显示多个列表。当前从一个开始,但我收到以下运行时错误:

System.Core 中发生类型为"Microsoft.CSharp.RuntimeBinder.RuntimeBinderException"的异常.dll但未在用户代码中处理

附加信息:"对象"不包含"所有基于位置的促销"的定义

using System.Text;
using System.Threading.Tasks;
namespace FreeRolla.BaseObjects
{
    class LocationBasedPromotion
    {
    public string Country { get; set; }
    public string City { get; set; }
    public string FlagIcon { get; set; }
    public int HotelCount { get; set; }
    public int StartingPrice { get; set; }
    public string WeatherIcon { get; set; }
    public string WeatherTemperature { get; set; }
    public string CityImage { get; set; }
    public List<LocationBasedPromotion> Promotions { get; set; }
}
}

using FreeRolla.BaseObjects;
namespace FreeRolla.BL
{
class HPLocationBasedPromotionProvider
{
    public List<LocationBasedPromotion> GetAllPromotions()
    {
        return new List<LocationBasedPromotion>{
            new LocationBasedPromotion{Country="UK", City="London", FlagIcon="", HotelCount=135, StartingPrice=350, CityImage="London.jpg", WeatherIcon="cloudy", WeatherTemperature="+18" },
            new LocationBasedPromotion{Country="Spain", City="Barcelona", FlagIcon="", HotelCount=215, StartingPrice=230, CityImage="Barcelona.jpg", WeatherIcon="sunny", WeatherTemperature="+28" },
            new LocationBasedPromotion{Country="Israel", City="Tel-Aviv", FlagIcon="", HotelCount=75, StartingPrice=280, CityImage="Tel-Aviv.jpg", WeatherIcon="sunny", WeatherTemperature="+32" }
        };
    }
}
}

using FreeRolla.BaseObjects;
using System.Web;
using System.Web.Mvc;

namespace FreeRolla.Models.ViewModels
{
class HomeView 
{
    public List<LocationBasedPromotion> allLocationBasedPromotions { get; set; }
}
}

using FreeRolla.BL;
using FreeRolla.Models.ViewModels;
namespace FreeRolla.Controllers
{
public class HomeController : Controller
{
    // GET: Home
    public ActionResult Index()
    {
        //return View();
        HPLocationBasedPromotionProvider _BigPromotions = new HPLocationBasedPromotionProvider();
        HomeView hv = new HomeView();
        hv.allLocationBasedPromotions = _BigPromotions.GetAllPromotions();
        return View(hv);
    }
}

}

从视图中 - 这里发生崩溃:

@foreach (var item in Model.allLocationBasedPromotions)

{

使用 ViewModel 时在 Razor 中的运行时崩溃

可能太明显了,但看起来您的视图文件缺少此

@model FreeRolla.Models.ViewModels.HomeView

编辑:

视图类应具有以下声明:

namespace FreeRolla.Models.ViewModels
{
    public class HomeView
    {
        public List<LocationBasedPromotion> allLocationBasedPromotions { get; set; }
    }
}

LocationBasedPromotion也应设为public。基本上,作为提示,让每个类都public在你的项目中,除非你有充分的理由不这样做。随着您获得更多经验,您会遇到一些情况,您将知道何时不参加public课程。但在你的情况下,只需让他们public.