Is it possible to add a route at runtime in MVC3?


I am creating a project in MVC3 along with C # for a local college. It was required to show the teacher profile when something like www.mysite.com/teachercode is entered in the browser.

I made the ShowTeacher method in the Teacher controller class. My plan is to search the database at application startup and register the same route for each teacher, as shown below, which will process the request further, is this approach correct?

foreach(Teacher tch in TeacherCollection)
routes.MapRoute(
            "Teacher route" + tch.Id,
            tch.TeacherCode,
            new { controller = "Teacher", action = "ShowTeacher" }
        );

Secondly, if a new teacher is added to the database, is it possible to add a route as soon as the teacher is saved?

Thanks in advance

+5
source share
1 answer

, , URL- www.mysite.com/teachercode, , .

RegisterRoutes ( ), ShowTeacher TeacherController, .

routes.MapRoute(
    "Teacher route", // route name
    "{teacherCode}", // url
    new { controller = "Teacher", action = "ShowTeacher" }, // defaults
    new { teacherCode = @"[A-Za-z]{1,10}" } // constraints
    );

- @"[A-Za-z]{1,10}" - , 1 10 . .

+5

All Articles