locked
Error Object does not exist in foreach on view, while it exists RRS feed

  • Question

  • User1886661451 posted

    I have a collection that I pass to a view using ViewBag. Then I iterate using foreach. I get the error "Object doesn't contain definition for ID". When I hover over the var I can see that the object is there, containing a property ID and a value.

    What am I doing wrong?

    This is the code in de controller:

    List<Zoekvelden> zoekvelden = new List<Zoekvelden>();

    var metatypes = (from mt in db.MetaTypes
                                    from qt in db.MetaType_QuestionTypes.Where(w => mt.MetaType_QuestionType_ID == w.ID && (mt.IsUserEntityMeta == true))
                                    select new { ID = mt.ID, Description = mt.Description, QuestionType = qt.Description }).ToList();

    foreach (var item in metatypes)

    {
        Zoekvelden zoekveld = new Zoekvelden();
        zoekveld.ID = item.ID;
        zoekveld.Description = item.Description;
        zoekveld.QuestionType = item.QuestionType;
        zoekvelden.Add(zoekveld);
    }

    ViewBag.Zoekvelden = zoekvelden;


    In the view:

    <div>
        @foreach (var type in ViewBag.Zoekvelden)
        {
            <span>
                @type.ID
            </span> <br />
        }
    </div>

    Tuesday, November 3, 2020 11:14 AM

Answers

All replies