Saturday, September 24, 2011

ASP.NET MVC Routing

  • Routing is used by the ASP.NET MVC framework to route incoming requests to controller actions. 
  • Routing uses a route table to handle incoming requests. This route table is created when your web application first starts. The route table is setup in the Global.asax file. 
  • When an ASP.NET application first starts, the Application_Start() method is called. This method calls the RegisterRoutes() method and the RegisterRoutes() method creates the default route table. 
  • The default route table consists of one route. This default route breaks all incoming requests into three segments (a URL segment is anything between forward slashes). 
  • The first segment is mapped to a controller name, the second segment is mapped to an action name, and the final segment is mapped to a parameter passed to the action named Id.
Example
    1)    Url: http://localhost /User/UserDetails/3
Controller = User, Action = UserDetails, Id = 3   

    2)    Url: http://localhost /User
Controller = User, Action = Index, Id = “”

The Default route defined in the Global.asax file includes default values for all three parameters. The default Controller is Home, the default Action is Index, and the default Id is an empty string. 

    3)    Url: http://localhost /
Controller = Home, Action = Index, Id = “”

More Examples
URL
Controller Class
Action Method
Parameter Passed
/User/UserDetails/1
User
UserDetails(id)
Id = 1
/User/EditUser/1
User
EditUser(id)
Id = 1
/User/CreateUser
User
CreateUser()
Id=””
/User
User
Index
Id=””
/
Home
Index
Id=””

No comments:

Post a Comment