Stuffing an anonymous type in ViewBag causing model binder issues

前端 未结 2 1926
不思量自难忘°
不思量自难忘° 2020-11-28 15:38

can someone tell me what I\'m doing wrong? :-)

I have this simple query:

 var sample = from training in _db.Trainings
              where training.In         


        
2条回答
  •  攒了一身酷
    2020-11-28 16:07

    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
    @foreach (var item in ViewBag.Sample) {
        @item.Something
    }
    

提交回复
热议问题