'object' does not contain a definition for 'Name'

北城以北 提交于 2020-01-14 09:10:06

问题


I'm using two DataContext objects to return seperate AsQueriable() datasets then joining the two using linq. The data construction works perfectly however when I pass that combined dataset to the view, I'm getting the error 'object' does not contain a definition for 'Name'.

During a debug session I can clearly see that both the parent Model and each 'item' in the foreach loop has all the data and keys visible/accessible. I'm very confused.

Many of the other q&a's on stackoverflow.com that match this problem don't solve my issue and as a result would appreciate a fresh set of eyes and hopefully a solution to this problem.

Many thanks! - code time:

The data construction

        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's error screen:

Any guidance on a solution would be greatly appreciated. Thank you!

C


回答1:


I would suggest you create a single model to encapsulate both IEnumerable objects, e.g.

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

Then strongly type your view to match the model

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

Then in your model, you can type-safely refer to each object, e.g.

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



回答2:


You're returning anonymous type to display in view, hence the problems. Take a look at those questions:

  • Can I pass an anonymous type to my ASP.NET MVC view?
  • LINQ to SQL: Return anonymous type?

You can either wrap your anonymous type in actual class and use strongly typed view, or play with some dynamic magic. Linked questions cover those topics.




回答3:


Try changing your for loop to:

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

The use of var is causing the type of t to be inferred as object.



来源:https://stackoverflow.com/questions/5742339/object-does-not-contain-a-definition-for-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!