devzim
devzim

Reputation: 153

OrderBy Linq expression in MVC5 asp.net View advice

I am currently filtering a page that has courses and projects associated to those courses. I want to order those projects by which one received the most vote dollars -- attribute vote_amount. I am having trouble figuring out how to handle this through the controller and i can easily do it in the view however, I receive an error.

I have a loop inside of a loop and it is working quite well so far but i need to order.

    foreach (var item in ViewBag.Courses)
    {
           <h2> item.CourseName <h2> 
           foreach (var project in item.Projects.OrderBy(project => project.vote_amount)
           { 
               <h2> project.Name <h2>
           }


     }

Seems to easy then i receive the following error. Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type

I know i should keep this stuff in the controller when in using linq expressions but, I am having trouble get the desired order by array of projects i want inside another loop. Any advice would be appreciated.

Upvotes: 1

Views: 448

Answers (1)

have you tried to order it before the foreach loop?

foreach (var item in ViewBag.Courses)
{
    <h2> item.CourseName <h2>
    item.Projects = item.Projects.OrderBy(project => project.vote_amount).toList(); 

    foreach (var project in item.Projects)
    { 
         <h2> project.Name <h2>
    }
}

Upvotes: 1

Related Questions