Stuffing an anonymous type in ViewBag causing model binder issues

This cannot be done. ViewBag is dynamic and the problem is that the anonymous type is generated as internal. I would recommend you using a view model:

public class Instructor
{
    public string Name { get; set; }
}

and then:

public ActionResult Index()
{
    var mdoel = from training in _db.Trainings
                 where training.InstructorID == 10
                 select new Instructor { 
                     Name = training.Instructor.UserName 
                 };
    return View(model);
}

and in the view:

@model IEnumerable<Instructor>
@foreach (var item in ViewBag.Sample) {
    @item.Something
}

Leave a Comment