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
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With