I am creating a project in MVC3 along with C# for a local college. The requirement was to show teacher profile when something like http://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
You don’t need to add a route at runtime, instead you can set up a route that will catch URLs of the form http://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 theShowTeacheraction method of yourTeacherController, along with a route constraint.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.