Is it possible to add route at runtime in MVC3?

asp.net-mvc-3, c#, routes

Solution

You don't need to add a route at runtime, instead you can set up a route that will catch URLs of the form www.mysite.com/teachercode, so long as none of your teachercodes have the same name as any of your controllers.

In `RegisterRoutes`, add another route (which needs to be the first one), which will route queries to the `ShowTeacher` action method of your `TeacherController`, along with a route constraint.

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

The constraint in this example - `@"[A-Za-z]{1,10}"` - is speciying that the teachercode will contain only upper or lowercase letters, and is between 1 and 10 characters long. You can adapt this to your needs.

Problem

I am creating a project in MVC3 along with C# for a local college. The requirement was to show teacher profile when something like www.mysite.com/teachercode is entered in browser. I have made a method ShowTeacher in my Teacher controller class. My Plan is to lookup database on application start and for every teacher register the same route as shown below, which will handle 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 in database, is it possible to add the route as soon as teacher is saved? Thanks in advance

Original source