使用ViewModel

时间:2015-06-15 20:06:51

标签: c# asp.net-mvc razor

我试图通过ViewModel显示多个列表。目前从一个开始,但我得到以下运行时错误:

  

类型' Microsoft.CSharp.RuntimeBinder.RuntimeBinderException'的例外情况发生在System.Core.dll中但未在用户代码中处理

其他信息:'对象'不包含' allLocationBasedPromotions

的定义
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)

{

1 个答案:

答案 0 :(得分:0)

可能太明显了,但看起来你的视图文件缺少这个

@model FreeRolla.Models.ViewModels.HomeView

编辑:

您的视图类应具有以下声明:

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

课程LocationBasedPromotion也应该public。基本上,作为一个提示,在项目中创建每个类public,除非你有充分的理由。随着您获得更多经验,您将遇到无法成为课程public的情况。但在你的情况下,只需将它们public