Vijay
Vijay

Reputation: 363

MVC - Call multiple controllers for a single view

I have a view displaying Students, Courses, Subjects all at once. I have 3 different controllers which get a model for each.

I don't want to merge 3 different models into a single model and then make a single controller call. Instead I want 3 different controllers and make 3 calls to these controllers. How to acheive this?

public class ABCController : Controller
{
    public ActionResult Students()
    {
        return View(RepositoryHelper.GetStudentList());
    }

    public ActionResult Courses()
    {
        return View(RepositoryHelper.GetCoursesList());
    }

    public ActionResult Subjects()
    {
        return View(RepositoryHelper.GetSubjectsList());
    }
}

--View

 using (Html.BeginForm("GetData", "University", FormMethod.Post, new { id = "parameters" }))
    {
        @:<table>
            @:<tr><td>
               @Html.DropDownList("Students")
            @:</tr></td>
            @:<tr><td>
               @Html.DropDownList("Courses")
            @:</tr></td>
            @:<tr><td>
               @Html.DropDownList("Subjects")
            @:</tr></td>
        @:</table>
        @:<p><input type='submit' value='Submit></p>
    }

Upvotes: 0

Views: 5513

Answers (3)

mlusiak
mlusiak

Reputation: 1054

You should wrap your models into ViewModel class and create view that inherits that viewmodel.

Upvotes: 3

Yngve B-Nilsen
Yngve B-Nilsen

Reputation: 9676

I would make partial views for Students, Courses and Subjects, and then use the @Html.RenderAction("Subjects", "ABCController")

to render the different parts

Upvotes: 1

Andrew Newland
Andrew Newland

Reputation: 824

Looking at what you are trying to do i would say ajax is the best approach. MVC already contains Jquery so i would recommend using it.

This way you can load the dropdown list for students first (passing from the controller) And once the user has selected a Student you can load the Cources and subjects. This way you could change your controllers methods to limit the results based on what they have selected.

If you want to persist with your route I'd do the work on the controller and create a model on the fly. I would say you could use a dynamic object but this does not pass from the controller to the view. To get around this you could use a Dictionary.

var data = new Dictionary() data.Add("subjects", RepositoryHelper.GetStudentList()) data.Add("Courses", RepositoryHelper.GetCoursesList()) data.Add("subjects", RepositoryHelper.GetSubjectsList()) return View(Data);

Personally I'd go for option 1.

Upvotes: 0

Related Questions