user793468
user793468

Reputation: 4966

displaying varying results in a view from same controller action

I have a controller which displays a list of CourseID in a view based on StudentID I provide. Here is the controller Action:

public ActionResult ShowCourseId(int StudentId)
{
    ViewData.Model = from c in course.vwCourse.Where(s => s.StudentID == StudentId)
                     group c by c.CourseID into g
                     select g.FirstOrDefault();

    return View();
}

The above controller may display one or many CourseID's depending on number of Courses a student has available in his or hers cart. Now, if a student has no courses available in his or hers cart, I want to display all the courses. Can I achieve this in the same controller action? or will I need an additional controller action displaying all courses?

Thanks in advance

Upvotes: 0

Views: 39

Answers (1)

Alex Moore
Alex Moore

Reputation: 3455

Sure, you probably just need to give the Model different data, as long as the types of each set are the same. If the empty cart / show all courses has a different type, you can also tell the framework to show a different View that corresponds to the "All Courses" model.

I have no idea how your object models are set up but here's a hack idea if both sets are collections of Course objects:

public ActionResult ShowCourseId(int StudentId)
{
    var studentCourses = (from c in course.vwCourse
                          where c.StudentID == StudentId
                          group c by c.CourseID into g
                          select g.FirstOrDefault()).ToList();

    if(studentCourses  == null || !studentCourses .Any())
    {
        studentCourses  = (from c in course.vwCourse
                           group c by c.CourseID into g
                           select g.FirstOrDefault()).ToList();
    }

    ViewData.Model = studentCourses;
    return View();
}

What is the type that the first query gives back? Is it a collection of Courses ?

Upvotes: 1

Related Questions