Recently, one of my colleagues asked me a question where his routing was not working as expected. Let me mention the exact URLs he was giving -
URL 1
http://localhost:port/StudentEnquiries/StudentEnquiries/44
URL 2
http://localhost:port/StudentEnquiries/StudentEnquiries/?StudentID=44
Now, his question was that when he was giving URL 1, he was not getting the expected output, which is 44; whereas, in URL 2, everything was working as expected.
And his code snippet was as below.
- public class RouteConfig
- {
- public static void RegisterRoutes(RouteCollection routes)
- {
- routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
-
- routes.MapRoute(
- name: "Default",
- url: "{controller}/{action}/{id}",
- defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
- );
- }
- }
He claimed that he didn’t change anything in his Route.Config file.
His Controller looks something like this.
- public ActionResult StudentEnquiries(string StudentID)
- {
- return Content(StudentID);
- }
The problem statement looks very straightforward. Any guesses, what went wrong with his code?
I’m sure most of you might have already figured out the solution. But for the sake of the rest of the readers, I’ll elaborate more on it.
The route mentioned in Route.Config file outlines the variables in the URL and the action parameter maps those URL variables to the input parameters.
So, basically, the ID has to be replaced with StudentId in routing parameter and we are done!
Hope you enjoyed this small tip. Happy troubleshooting.