tags:

views:

13

answers:

1

Hi guys,

I am outputting a students logged problems by passing the student into the view and then accessing their problems like this:

foreach (var item in Model.Student.Problems) {

I was wandering how I could sort these items by the ProblemDateTime attribute? I notice when I put a . after Problems there is a OrderByDescending option by I am not entirely sure how to use it?

Any help would be appreciated.

Thanks,

Jon

A: 

I would tend to use a different ViewModel that consist of a Student and Problems as different properties

public class MyViewModel
{
    public Student Student { get; set; }
    public IList<Problem> Problems { get; set; }
}

Then your Controller should be responsible for returning the Student and the correct Problems

public ActionResult MyAction(int studentID)
{
    var model = new MyViewModel();

    //below is just an example:
    //would be much better if you had a service/repository layer 
    //that you could call to return your information

    model.Student = _db.Students.FirstOrDefault(s => d.ID == studentID);
    model.Problems = _db.Problems.Where(p => p.StudentID == studentID)
        .OrderByDescenging(p => p.Date)
        .ToList();

    return View(model);
}
David Liddle
Thanks this worked, I was just trying to use the bindings LINQ makes between objects to access the problems in the view without having to put extra code in the controller. But it seems this is the only way to get them to order.
Jonathan Stowell
All querying logic should be handled in the Controller and not the View.
David Liddle