Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to add route at runtime in MVC3?


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

like image 822
Imran Balouch Avatar asked May 28 '12 11:05

Imran Balouch


People also ask

How can add route in ASP.NET MVC?

In MVC, routing is a process of mapping the browser request to the controller action and return response back. Each MVC application has default routing for the default HomeController. We can set custom routing for newly created controller. The RouteConfig.

Can we add constraints to the route if yes explain how we can do it?

Creating Route Constraint to a Set of Specific Values MapRoute( "Default", // Route name "{controller}/{action}/{id}", // Route Pattern new { controller = "Home", action = "Index", id = UrlParameter. Optional }, // Default values for parameters new { controller = "^H.

Can we have multiple routing in MVC?

Multiple Routes You need to provide at least two parameters in MapRoute, route name, and URL pattern. The Defaults parameter is optional. You can register multiple custom routes with different names.


1 Answers

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.

like image 98
Richard Ev Avatar answered Oct 12 '22 08:10

Richard Ev