A Tip On MVC URL Routing

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 - 





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.
  1. public class RouteConfig  
  2.     {  
  3.         public static void RegisterRoutes(RouteCollection routes)  
  4.         {  
  5.             routes.IgnoreRoute("{resource}.axd/{*pathInfo}");  
  7.             routes.MapRoute(  
  8.                 name: "Default",  
  9.                 url: "{controller}/{action}/{id}",  
  10.                 defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }  
  11.             );  
  12.         }  
  13.     }  

He claimed that he didn’t change anything in his Route.Config file.

His Controller looks something like this.

  1. public ActionResult StudentEnquiries(string StudentID)  
  2.         {  
  3.             return Content(StudentID);  
  4.         }  

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.

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now