在一个路由中指定多个控制器

时间:2015-09-02 20:59:14

标签: asp.net asp.net-mvc routing asp.net-mvc-controller

在我们的ASP.NET MVC架构中,我们有以下路由结构:

http://localhost:80/Students/Details/2 - will give me details about student with id == 2, details include all the classes current student have.

http://localhost:80/Classes/Details/2 - will give me details about classes with id == 2, details include all the students current class have.

http://localhost:80/Schedule/Details/class=2&student=2 - will give me details about specific schedule for student with id=2 that has class with id=2

到目前为止,此工作正常。

现在,我们的团队对asp.net mvc来说还是一个新手,我们正在考虑使路由更直观。因此,我们将使用一条很长的路线而不是三条独立的路线,如下所示:

http://localhost:80/Students/2/Classes/2/Homework/ 

它将起作用:

http://localhost:80/Students/ - will give list of students
http://localhost:80/Students/2 - will give details about student 2
http://localhost:80/Students/2/Classes - will give all the classes for student with id 2
http://localhost:80/Students/2/Classes/2 - will give schedule for class with id 2 and student with id 2. 

不确定是否合理/可能,只是想获得更多意见

1 个答案:

答案 0 :(得分:1)

MVC路由映射到控制器类内的单个操作 您可以为每个案例配置一个路由,映射到每个案例的不同操作。请记住,路线应该从更具体到更通用的方式放置。

在App_Start / RouteConfig.cs中:

        routes.MapRoute(
            name: "StudentSchedule",
            url: "students/{studentID}/classes/{classID}",
            defaults: new { controller = "Home", action = "StudentSchedule" }
        );
        routes.MapRoute(
            name: "StudentClasses",
            url: "students/{studentID}/classes",
            defaults: new { controller = "Home", action = "StudentClasses" }
        );
        routes.MapRoute(
            name: "StudentDetails",
            url: "students/{studentID}",
            defaults: new { controller = "Home", action = "StudentDetails" }
        );
        routes.MapRoute(
            name: "StudentsList",
            url: "students",
            defaults: new { controller = "Home", action = "Students" }
        );

因此,您的操作将如下所示,您必须添加代码才能从数据库中获取数据,您可以在应用程序的sepparated类/层上共享代码:

    public ActionResult Students()
    {
        var viewmodel = new StudentsViewModel();
        ...
        return View(viewmodel);
    }

    public ActionResult StudentDetails(int studentID)
    {
        var viewmodel = new StudentDetailsViewModel();
        ...
        return View(viewmodel);
    }

    public ActionResult StudentClasses(int studentID)
    {
        var viewmodel = new StudentClassesViewModel();
        ...
        return View(viewmodel);
    }

    public ActionResult StudentSchedule(int studentID, int classID)
    {
        var viewmodel = new StudentScheduleViewModel();
        ...
        return View(viewmodel);
    }