0

I am not having a problem so much with the query as accessing the data or setting it up so I can pass it to the view.

Here's the expression

  var distinctReplies = pd.Project.ProjectDoc
        .SelectMany(i => i.Comment
            .SelectMany(k => k.CommentReply
                .Select(u => u.User)
            ).Distinct()
        ).Select(g => new {FirstName = g.FirstName, LastName = g.LastName, UserID = g.UserID})
        .ToList();

After this expression I want to concat it with another one that is getting values from the same user model, I want to assign distinctReplies to a ViewBag variable and then be able to loop though it and do this foreach (var user in @ViewBag.distinctReplies) in a razor view.

However, to actually get at the values I have to do distinctReplies.Select(i => i.FirstName). Not sure how to deal with this.

spajce
  • 7,044
  • 5
  • 29
  • 44
Jed Grant
  • 1,305
  • 1
  • 17
  • 47

2 Answers2

1

Use this:

@foreach (var reply in (IEnumerable)ViewBag.distinctReplies) 
{
}

You cannot enumerate an instance of a dynamic. Cast it to an IEnumerable for the statement to be allowed.

See this question for a more thorough explanation.

Community
  • 1
  • 1
Paul Fleming
  • 24,238
  • 8
  • 76
  • 113
  • How would you acces the original properties of reply `object`? – mipe34 Jan 22 '13 at 22:13
  • You can't without reflection at this point. You should not use an anonymous type as your view model. Implement a ViewModel like suggested in @mipe34's answer. Then you can replace the `var` with `YourType`. – Paul Fleming Jan 22 '13 at 22:19
1

I would suggest to create some ViewModel object for populating the query result. To be able to access the properties inside the @foreach loop.

Model

public class UserVM
{
    public int UserID{get; set;}
    public string FirstName {get; set;}
    public string LastName {get; set;}  
}

Updated query

  var distinctReplies = ....
                .Select(g => new UserVM {FirstName = g.FirstName, 
                                         LastName = g.LastName, 
                                         UserID = g.UserID}).ToList();

Then, in the view, you will need to add cast to IEnumerable<UserVM>.

View

@foreach (var user in (IEnumerable<UserVM>) ViewBag.distinctReplies)
mipe34
  • 5,596
  • 3
  • 26
  • 38
  • This isn't exactly what I did, but it put me on the right track, I added a "User" model to the existing viewmodel and assigned it and that worked. – Jed Grant Jan 22 '13 at 22:02
  • If you've created a model, then shouldn't be using ViewBag. Return the model set to the view: `return View("MyView", mymodelset);`. – Paul Fleming Jan 22 '13 at 22:05
  • Of course, better way would be to **not** putting it in `ViewBag` at all. And use strongly typed view. – mipe34 Jan 22 '13 at 22:12