【问题标题】:ASP.NET MVC - 'object' does not contain a definition for 'ID'ASP.NET MVC -“对象”不包含“ID”的定义
【发布时间】:2015-07-09 07:16:13
【问题描述】:

我收到错误:对象不包含“样式代码”的定义。事实上,当我在断点上检查它时,我得到了模型中的记录列表我错过了什么?

HomeController.cs

public ActionResult Index()
{
    using (var context = new ApronPointEntities())
    {
        var styles = (from s in context.STYLEs
            join
            c in context.STYLEPRICEs on s.STYLEID equals c.STYLEID
            select new {
                STYLEID=s.STYLEID,
                STYLECODE=s.STYLECODE,
                STYLENAME= s.STYLENAME,
                PRICE= c.REGULARPRICE
            }).Take(10).OrderByDescending(s =>s.STYLEID).ToList();

        return View(styles);
    }
}

-------------Index.cshtml--------------

@foreach(var item in Model)
{ 
    <div class="col-md-3 col-xs-6">
        <div class="product">
            <div class="product-cover">
                <span class="product-action">
                    <span class="product-new">New</span>
                    <span class="product-sale">Sale</span>
                </span>
                <div class="product-cover-hover"><span><a href="product.html">View</a></span></div>
                <img src="~/Images/Styles/Img-0.jpg" />
            </div>
            <div class="product-details">
                <h1><a href="product.html">@item.STYLECODE</a></h1>
                <p>@item.STYLENAME</p>
                <div class="product-price">
                    <i class="icon-257" title="add to cart"></i>
                    @item.PRICE
                </div>
            </div>
        </div>
    </div>
}

【问题讨论】:

  • 你正在返回一个匿名对象的集合,创建一个代表它的类会很棒!
  • @StuartLC 它是一个列表 Model ={System.Collections.Generic.Listf__AnonymousType1>}

标签: c# asp.net asp.net-mvc-4


【解决方案1】:

我想推荐你参加一个班级,即ViewModel

public class ViewModel
{
    public int STYLEID { get; set; }
    public string STYLECODE { get; set; }
    public string STYLENAME { get; set; }
    public double PRICE { get; set; }
}

.cshtml文件一个List&lt;ViewModel&gt;

【讨论】:

    【解决方案2】:

    @foreach(var item in Model) 'var' 在这里解析的类型是什么?

    它很可能是一个对象。您应该先将其转换为您的类型,然后才能访问它的某些成员。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-31
      • 1970-01-01
      • 1970-01-01
      • 2013-08-27
      • 1970-01-01
      • 1970-01-01
      • 2016-10-03
      • 2017-02-13
      相关资源
      最近更新 更多