Thursday, February 8, 2018

Tip on MVC URL Routing

Recently, one of my colleague asked me a question, in which his routing was not working as expected. Let me mention the exact URL he was giving:

URL 1:
http://localhost:port/StudentEnquiries/StudentEnquiries/44

URL 2:
http://localhost:port/StudentEnquiries/StudentEnquiries/?StudentID=44 

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 } 
            ); 
        } 
    }    

Where he claimed that he didn’t change anything in his Route.Config file and his Controller looks something like this:
  public ActionResult StudentEnquiries(string StudentID) 
  { 
        return Content(StudentID); 
  }     

Now his question was, when he is giving URL 1, he is not getting the expected output, which is 44 whereas in URL 2 everything was working as expected.
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 rest of the readers, I’ll elaborate more on it.
The route mentioned in Route.Config file outlines variables in the URL and the action parameter maps those URL variables to input parameters.


So, basically id has to be replaced with StudentId in routing parameter and we are done.
Hope you enjoyed this small tip. Happy troubleshooting.

No comments:

Post a Comment