的foreach ViewBag数据给出了“对象”不包含“无功”的定义 [英] Foreach ViewBag data gives 'object' does not contain a definition for 'var'

查看:212
本文介绍了的foreach ViewBag数据给出了“对象”不包含“无功”的定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个控制器,它正在建设一个查询的LINQ到SQL来传递到ViewBag.products对象。问题是,我不能使用foreach它循环如我所料我可以。

I have a controller that is building a query from Linq to Sql to pass into the ViewBag.products object. The problem is, I cannot loop using a foreach on it as I expected I could.

这里的code控制器构建查询,应用了.ToList()函数。

Here's the code in the controller building the query, with the .ToList() function applied.

var products = from bundles in db.Bundle
    join bProducts in db.BundleProducts on bundles.bundleId equals bProducts.bundleID
    join product in db.Products on bProducts.productID equals product.productID
    join images in db.Images on product.productID equals images.productID
    where bundles.bundleInactiveDate > DateTime.Now
          select new {
              product.productName,
              product.productExcerpt,
              images.imageID,
              images.imageURL
           };
ViewBag.products = products.ToList();

由于我使用需要其他项目上Index.cshtml不同的模式,我想简单的Html.Partial可用于包括viewbag循环。我已经用和不使用的部分,并只需在index.cshtml使用foreach同样的结果试了一下。这包括部分摘要是如下:

Since I am using a different model on the Index.cshtml for other items needed, I thought a simple Html.Partial could be used to include the viewbag loop. I have tried it with the same result with and without using the partial and simply by using the foreach in the index.cshtml. A snippet that includes the partial is below:

<div id="bundle_products">
<!--build out individual product icons/descriptions here--->
@Html.Partial("_homeBundle")
</div>

在我_homeBundle.cshtml文件我有以下几点:

In my _homeBundle.cshtml file I have the following:

@foreach (var item in ViewBag.products)
{ 
    @item
}

我收到ViewBag数据,但我得到了整个列表,这样的输出:

I am getting the ViewBag data, but I am getting the entire list as output as such:

{ productName = Awesomenes Game, productExcerpt = <b>Awesome game dude!</b>, imageID = 13, imageURL = HotWallpapers.me - 008.jpg }{ productName = RPG Strategy Game, productExcerpt = <i>Test product excerpt</i>, imageID = 14, imageURL = HotWallpapers.me - 014.jpg }

我想我可以做的是:

What I thought I could do was:

@foreach(var item in ViewBag.Products)
{
    @item.productName
}

如你所见,输出,产品名称= Awesomenes游戏。但是,我得到的错误'对象'不包含定义为产品名称,当我尝试这一点。

As you can see, in the output, productName = Awesomenes Game. However, I get the error 'object' does not contain a definition for 'productName' when I attempt this.

我怎么能输出每一个场,所以单独说,在我的循环,所以我可以申请必要的适当的HTML标签和造型为我的网页?

How can I output each "field" so to say individually in my loop so I can apply the proper HTML tags and styling necessary for my page?

我需要做一个全新的视图模型要做到这一点,然后创建一个显示模板此处引用:<一href=\"http://stackoverflow.com/questions/7652749/object-does-not-contain-a-definition-for-x\">'object'不包含'X'

Do I need to make a whole new ViewModel to do this, and then create a display template as referenced here: 'object' does not contain a definition for 'X'

或者我可以做什么,我试图在这里?

Or can I do what I am attempting here?

的* UPDATE ***

*UPDATE***

在我的控制器我现在有以下几点:

In my Controller I now have the following:

        var bundle = db.Bundle.Where(a => a.bundleInactiveDate > DateTime.Now);
        var products = from bundles in db.Bundle
                       join bProducts in db.BundleProducts on bundles.bundleId equals bProducts.bundleID
                       join product in db.Products on bProducts.productID equals product.productID
                       join images in db.Images on product.productID equals images.productID
                       where bundles.bundleInactiveDate > DateTime.Now
                       select new {
                           product.productName,
                           product.productExcerpt,
                           images.imageID,
                           images.imageURL
                       };
        var bundleContainer = new FullBundleModel();

        bundleContainer.bundleItems = bundle;

        return View(bundleContainer);

我有一个模型,FullBundleModel

I have a model, FullBundleModel

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace JustBundleIt.Models
{
    public class FullBundleModel
    {
        public IQueryable<Bundles> bundleItems { get; set; }
        public IQueryable<Images> imageItems { get; set; }
    }
}

和我查看现在有

@model IEnumerable<JustBundleIt.Models.FullBundleModel>

@foreach (var item in Model) 
{
<div class="hp_bundle">

    <h3>@Html.Display(item.bundleName)</h3>
    </div>
}       

如果我删除该模型参考了IEnumerable,在foreach出现了错误,有一个枚举没有公共的定义。

If I remove IEnumerable from the model reference, the foreach errors out that there is no public definition for an enumerator.

在@ Html.Display(item.bundleName)就出现了错误,该模型对束名称没有定义。如果我试图

In the @Html.Display(item.bundleName) it errors out that the model has no definition for bundleName. If I attempt

@foreach(var item in Model.bundleItems)

我得到bundleItems未在模型中定义一个错误。

I get an error that bundleItems is not defined in the model.

那么,不要我了有线正确使用相结合的模式?

So what don't I have wired up correctly to use the combined model?

推荐答案

为什么不创建一个包含一个新的模型所有你需要的数据的?

Why not create a new model that contains all of the data that you need?

例一:

public class ContainerModel
{
    public IQueryable<T> modelOne;
    public IQueryable<T> modelTwo;
}

这将允许您访问或者您的查询的剃刀:

This will allow you to access either of your queries in Razor:

@model SomeNamespace.ContainerModel

@foreach (var item in Model.modelOne)
{
    //Do stuff
}

我个人避免全部采用ViewBag并保存一切,我需要这样的模型,因为它是不是动态的,需要强类型部队的一切。我也相信,这给你一个明确的结构/意图。

I personally avoid using ViewBag at all and store everything I need in such models because it's NOT dynamic and forces everything to be strongly typed. I also believe that this gives you a clearly defined structure/intent.

和只是为了清楚起见:

public ViewResult Index()
{
    var queryOne = from p in db.tableOne
                   select p;

    var queryTwo = from p in db.tableTwo
                   select p;

    var containerModel = new ContainerModel();
    containerModel.modelOne = queryOne;
    containerModel.modelTwo = queryTwo;

    return View(containerModel);
}

例二:

public class ContainerModel
{
    [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")] //Format: MM/dd/yyyy (Date)
    public Nullable<DateTime> startDate { get; set; }
    [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")] //Format: MM/dd/yyyy (Date)
    public Nullable<DateTime> endDate { get; set; }
    public SelectList dropdown { get; set; }
    public IQueryable<T> modelOne { get; set; }
    public IQueryable<T> modelTwo { get; set; }
}

在这种情况下,你已经存储在模型3其他项目与2查询。您可以使用HTML佣工剃刀创建一个下拉列表:

In this case you've stored 3 other items in the model with your 2 queries. You can use the Html helpers to create a Drop Down List in Razor:

@Html.DropDownList("dropdown", Model.dropdown)

和您可以使用DisplayFor助手来显示您所选的日期作为与数据注释模型中定义:

And you can use the DisplayFor helper to display your dates as defined in your model with Data Annotations:

@Html.DisplayFor(a => a.startDate)

这是IMO有利的,因为它允许您定义的所有数据,你想利用你的视图,您打算如何格式化在一个地方的数据。控制器包含了所有的业务逻辑,模型中包含的所有数据/格式化的,你的视图只关心你的网页的内容。

This is advantageous IMO because it allows you to define all of the data that you want to make use of in your View AND how you plan to format that data in a single place. Your Controller contains all of the business logic, your Model contains all of the data/formatting, and your View is only concerned with the content of your page.

这篇关于的foreach ViewBag数据给出了“对象”不包含“无功”的定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆