1

I have this LINQ...

var n = from a in this.DataContext.News select new { a.ID, a.Name, a.StartDate, a.EndDate, SportName = (from v in this.DataContext.Sports where v.ID == a.SportID select v).FirstOrDefault()};

ViewData["News"] = n.ToList();

And I need to generate a HTML table. I cannot figured out how to get items from ViewData["News"]. Any clue?

<% foreach (var item in (???) ViewData["News"])
                   { %> ...

UPDATES:

I found this post It seems I have to create 1 extra class NewsView which is going to have all selected fields. And then I can cast to NewsView... Is there other way to do it?

 var n= from a in this.DataContext.News
                      select new NewsView { ID = a.ID, Name = a.Name, StartDate = a.StartDate, EndDate = a.EndDate, 
                                  SportName = (from v in this.DataContext.Sports where v.ID == a.SportID select v).FirstOrDefault().Name};

and

 <% foreach (var item in (IEnumerable<MyProject.ViewModels.NewsView>)ViewData["News"])
                   { %>

1 Answer 1

1

The best thing to do will be to create a class in your model so that you have a List items to assign your data to and then to repeat through rather than using ViewData or Viewbags. Then in your foreach loop, the var item will have dot (.) properties.

@foreach (var item in Model.myClassItems)
{
      <div>@item.classproperty</div>
}
Sign up to request clarification or add additional context in comments.

2 Comments

This would be using stronly typed data properties giving you the visibility in the view that you need
Thanks for the input, bro! I found the solution. It is under UPDATES:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.