开发者

MVC - Call multiple controllers for a single view

开发者 https://www.devze.com 2023-02-20 00:03 出处:网络
I have a view displaying Students, Courses, Subjects all at once. I have 3 different controllers which get a model for each.

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>
    }


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


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

to render the different parts


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消