簡體   English   中英

'object'不包含'Name'的定義

[英]'object' does not contain a definition for 'Name'

我使用兩個DataContext對象返回單獨的AsQueriable()數據集,然后使用linq連接兩個。 數據構造工作完美,但是當我將組合數據集傳遞給視圖時,我得到的錯誤“對象”不包含“名稱”的定義。

在調試會話期間,我可以清楚地看到父模型和foreach循環中的每個“項”都具有可見/可訪問的所有數據和鍵。 我很困惑。

stackoverflow.com上與此問題相關的許多其他q&a都沒有解決我的問題,因此會欣賞一雙新鮮的眼睛並希望能夠解決這個問題。

非常感謝! - 代碼時間:

數據構建

        public ActionResult SplashImages()
        {
            var g = (from i in GetGallerySplash() join o in GetFestivals() on i.Festival equals o.ID orderby i.Rating descending select new {i.Photo, i.OwnedBy, i.Rating, o.Name });
            Response.ContentType = "text/xml";
            return View(g);
        }

        private IEnumerable<Gallery> GetGallerySplash()
        {
            GallerysDataContext gdc = new GallerysDataContext();
            return (from i in gdc.Galleries orderby i.Rating descending select i).Take(15).AsQueryable();
        }

        private IEnumerable<Festival> GetFestivals()
        {
            FestivalsDataContext fdc = new FestivalsDataContext();
            return (from i in fdc.Festivals select i).AsQueryable();
        }

VSExpress的錯誤屏幕: 例外截圖

任何有關解決方案的指導都將不勝感激。 謝謝!

C

我建議你創建一個單獨的模型來封裝IEnumerable對象,例如

public class GalleryModel
{
    public IEnumerable<Gallery> Galleries { get; set }
    public IEnumerable<Festivals> Festivals { get; set; }
}

然后強烈鍵入您的視圖以匹配模型

...Inherits="System.Web.Mvc.ViewPage<GalleryModel>"

然后在您的模型中,您可以鍵入 - 安全地引用每個對象,例如

<% foreach (var t in Model.Galleries) ...

您將返回匿名類型以在視圖中顯示,因此存在問題。 看看這些問題:

您可以將您的匿名類型包裝在實際類中,並使用強類型視圖,或者使用一些動態魔法。 鏈接問題涵蓋了這些主題。

嘗試將for循環更改為:

<% foreach (dynamic t in Model) { %>

var的使用導致t的類型被推斷為object

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM