8

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

I have this simple query:

 var sample = from training in _db.Trainings
              where training.InstructorID == 10
              select new { Something = training.Instructor.UserName };

And I pass this to ViewBag.

ViewBag.Sample = sample;

Then I want to access it in my view like this:

@foreach (var item in ViewBag.Sample) {
    @item.Something
}

And I get error message 'object' does not contain a definition for 'Something'. If I put there just @item, I get result { Something = SomeUserName }

Thanks for help.

one.beat.consumer
  • 9,414
  • 11
  • 55
  • 98
Iškuda
  • 635
  • 1
  • 7
  • 13

2 Answers2

17

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
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • 1
    +1 - Notice how he's selecting a `new Instructor` a concrete type - not an anonymous type. That way he can access the information within the object. – Only Bolivian Here Apr 13 '11 at 13:01
0

If you want to send in ViewData For example and don't want to send in model you could use the same could as in the upper answer and in the Controller

enter code here


ViewData[Instractor] = from training in _db.Trainings
                 where training.InstructorID == 10
                 select new Instructor { 
                     Name = training.Instructor.UserName 
                 };

and in the view you need to cast this to

`IEnumerable<Instructor>`

but to do this you should use

@model IEnumerable<Instructor>

Then you could do something like this

IEnumerable<instructors> Instructors =(IEnumerable<Instructor>)ViewData[Instractor];

then go with foreach

@foreach (var item in Instructors ) {
    @item.Something
}
Mohamed Fathallah
  • 1,274
  • 1
  • 15
  • 17