SlideShare une entreprise Scribd logo
1  sur  5
Télécharger pour lire hors ligne
7/16/2014 Understanding Routing in ASP.NET MVC with example
http://www.dotnet-stuff.com/tutorials/aspnet-mvc/understanding-routing-in-asp-net-mvc-with-example 1/5
R
Understanding Routing in ASP.NET MVC with example
Posted Date: 26. May 2014 Posted By: Anil Sharma
Categories: ASP.NET MVC, ASP.NET
Keywords: Routing in ASP.NET MVC, MVC Routing Example, Routing in MVC, Define Routing
outing in Asp.NET MVC is how ASP.NET MVC matches a URI to an action. ASP.NET routing enables you to
use URLs that do not have to map to specific files in a Web site. Because the URL does not have to map to a
file, you can use URLs that are descriptive of the user's action and therefore are more easily understood by users. It
is a part of all the MVC versions but MVC 5 supports a new type of routing, called attribute routing. As the name
implies, attribute routing uses attributes to define routes. Attribute routing gives you more control over the URIs in
your web application. There is a separate article to understand Attributes in Routing in ASP.NET MVC.
How to define Routing in MVC?
If you adopt the MVC convention of implementing controllers by creating classes that derive from the ControllerBase
class and giving them names that end with "Controller", you do not need to manually add routes in an MVC
application. The preconfigured routes will invoke the action methods that you implement in the controller classes.
You may also want to add custom routes in an MVC application, than you need to use the
MapRoute(RouteCollection, String, String) method instead of the MapPageRoute(String, String, String) method.
Once you have decide the Routing for your application, you need to register it and make sure that you are calling
this register method at Application_Start() event of your application. The following example shows the code that
creates default MVC routes in the Global.asax file, as defined in the Visual Studio project template for MVC
applications.
 


1
2
3
4
5
6
7
8
9
10
publicclassMvcApplication:System.Web.HttpApplication
{
publicstaticvoidRegisterRoutes(RouteCollectionroutes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", //Routename
"{controller}/{action}/{id}", //URLwithparameters
new{controller="Home",action="Index",id=""} //Parameterdefaultsvaluefor
7/16/2014 Understanding Routing in ASP.NET MVC with example
http://www.dotnet-stuff.com/tutorials/aspnet-mvc/understanding-routing-in-asp-net-mvc-with-example 2/5
Always remember route name should be unique across the entire application. Route name can’t be duplicate.
How to set Default Value for Routing in ASP.NET MVC?
Now you are able to define the routing in MVC. When you define a route, than you can still assign a default value for
a parameter. This default value is used if a value for that parameter is not included in the URL. You can set default
values for a route by assigning a dictionary object to the Defaults property of the Route class. The following example
shows how to add a route that has default values, by using the MapPageRoute(String, String, String, Boolean,
RouteValueDictionary) method.
As you can see in above code, ASP.NET routing handles a URL request, the route definition shown in the example
(with default values of MVC for categoryName and show for action) produces the results that are listed in the
following table.
URL Parameter values
11
12
13
14
15
16
17
18
19
);
}
protectedvoidApplication_Start()
{
RegisterRoutes(RouteTable.Routes);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
publicstaticvoidRegisterRoutes(RouteCollectionroutes)
{
routes.MapPageRoute("",
"Category/{action}/{categoryName}",
"~/categories.aspx",
true,
newRouteValueDictionary
{{"categoryName","MVC"},{"action","show"}});
}
voidApplication_Start(objectsender,EventArgse)
{
RegisterRoutes(RouteTable.Routes);
}
7/16/2014 Understanding Routing in ASP.NET MVC with example
http://www.dotnet-stuff.com/tutorials/aspnet-mvc/understanding-routing-in-asp-net-mvc-with-example 3/5
/Category
action = "show" (default value)
categoryName = "MVC" (default value)
/Category/add
action = "add"
categoryName = "MVC" (default value)
/Category/add/routingexample action = "add" categoryName= "routingexample"
How Routing is work in ASP.NET MVC?
To make better understanding of work flow of MVC Routing consider a diagram given below.
In above diagram, you can see that when any user make request for any URL, the system check in
RouteTable.Routes (Collection of all the Routes). It parses the route and match with current URL. If there are any
constraints or attributes are found than it process the constraints and check whether it satisfy than it will Build and
7/16/2014 Understanding Routing in ASP.NET MVC with example
http://www.dotnet-stuff.com/tutorials/aspnet-mvc/understanding-routing-in-asp-net-mvc-with-example 4/5
returns RouteData and page will be served , otherwise it will returns null and Page Not Found with Status code 404
can be returned.
To understand how Routing is works in MVC at macro level, we have following diagram shows how it is done.
The main function of the UrlRoutingModule is to tell the IIS to use IHttpHandler which I got from the matched route.
And IIS do the same and returns the result to the browser.
Summary: I Hope you have enjoyed this article and now you are able to define routing in ASP.NET MVC application.
Although, you need to know something more about attributes in Routing. Thus I have written this in a separate
article to understand attributes in Routing in ASP.NET MVC.
Keen to here from you...!
If you have any questions related to what's mentioned in the article or need help with any issue, ask it, I would love to
here from you. Please MakeUseOf Contact and i will be more than happy to help.
About the author
Anil Sharma is Chief Editor of dotnet-stuff.com. He's a software professional
and loves to work with Microsoft .Net. He's usually writes articles about .Net
related technologies and here to shares his experiences, personal notes,
7/16/2014 Understanding Routing in ASP.NET MVC with example
http://www.dotnet-stuff.com/tutorials/aspnet-mvc/understanding-routing-in-asp-net-mvc-with-example 5/5
Tutorials, Examples, Problems & Solutions, Code Snippets, Reference
Manual and Resources with C#, Asp.Net, Linq , Ajax, MVC, Entity
Framework, WCF, SQL Server, jQuery, Visual Studio and much more...!!!
Connect with the author: • Google + • Linkedin

Contenu connexe

Dernier

"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 

Dernier (20)

"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 

En vedette

How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthThinkNow
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfmarketingartwork
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsKurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summarySpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project managementMindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...RachelPearson36
 
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Applitools
 
12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at WorkGetSmarter
 

En vedette (20)

How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
 
12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work
 
ChatGPT webinar slides
ChatGPT webinar slidesChatGPT webinar slides
ChatGPT webinar slides
 

Understanding Routing in ASP.NET MVC with example

  • 1. 7/16/2014 Understanding Routing in ASP.NET MVC with example http://www.dotnet-stuff.com/tutorials/aspnet-mvc/understanding-routing-in-asp-net-mvc-with-example 1/5 R Understanding Routing in ASP.NET MVC with example Posted Date: 26. May 2014 Posted By: Anil Sharma Categories: ASP.NET MVC, ASP.NET Keywords: Routing in ASP.NET MVC, MVC Routing Example, Routing in MVC, Define Routing outing in Asp.NET MVC is how ASP.NET MVC matches a URI to an action. ASP.NET routing enables you to use URLs that do not have to map to specific files in a Web site. Because the URL does not have to map to a file, you can use URLs that are descriptive of the user's action and therefore are more easily understood by users. It is a part of all the MVC versions but MVC 5 supports a new type of routing, called attribute routing. As the name implies, attribute routing uses attributes to define routes. Attribute routing gives you more control over the URIs in your web application. There is a separate article to understand Attributes in Routing in ASP.NET MVC. How to define Routing in MVC? If you adopt the MVC convention of implementing controllers by creating classes that derive from the ControllerBase class and giving them names that end with "Controller", you do not need to manually add routes in an MVC application. The preconfigured routes will invoke the action methods that you implement in the controller classes. You may also want to add custom routes in an MVC application, than you need to use the MapRoute(RouteCollection, String, String) method instead of the MapPageRoute(String, String, String) method. Once you have decide the Routing for your application, you need to register it and make sure that you are calling this register method at Application_Start() event of your application. The following example shows the code that creates default MVC routes in the Global.asax file, as defined in the Visual Studio project template for MVC applications.     1 2 3 4 5 6 7 8 9 10 publicclassMvcApplication:System.Web.HttpApplication { publicstaticvoidRegisterRoutes(RouteCollectionroutes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( "Default", //Routename "{controller}/{action}/{id}", //URLwithparameters new{controller="Home",action="Index",id=""} //Parameterdefaultsvaluefor
  • 2. 7/16/2014 Understanding Routing in ASP.NET MVC with example http://www.dotnet-stuff.com/tutorials/aspnet-mvc/understanding-routing-in-asp-net-mvc-with-example 2/5 Always remember route name should be unique across the entire application. Route name can’t be duplicate. How to set Default Value for Routing in ASP.NET MVC? Now you are able to define the routing in MVC. When you define a route, than you can still assign a default value for a parameter. This default value is used if a value for that parameter is not included in the URL. You can set default values for a route by assigning a dictionary object to the Defaults property of the Route class. The following example shows how to add a route that has default values, by using the MapPageRoute(String, String, String, Boolean, RouteValueDictionary) method. As you can see in above code, ASP.NET routing handles a URL request, the route definition shown in the example (with default values of MVC for categoryName and show for action) produces the results that are listed in the following table. URL Parameter values 11 12 13 14 15 16 17 18 19 ); } protectedvoidApplication_Start() { RegisterRoutes(RouteTable.Routes); } } 1 2 3 4 5 6 7 8 9 10 11 12 13 publicstaticvoidRegisterRoutes(RouteCollectionroutes) { routes.MapPageRoute("", "Category/{action}/{categoryName}", "~/categories.aspx", true, newRouteValueDictionary {{"categoryName","MVC"},{"action","show"}}); } voidApplication_Start(objectsender,EventArgse) { RegisterRoutes(RouteTable.Routes); }
  • 3. 7/16/2014 Understanding Routing in ASP.NET MVC with example http://www.dotnet-stuff.com/tutorials/aspnet-mvc/understanding-routing-in-asp-net-mvc-with-example 3/5 /Category action = "show" (default value) categoryName = "MVC" (default value) /Category/add action = "add" categoryName = "MVC" (default value) /Category/add/routingexample action = "add" categoryName= "routingexample" How Routing is work in ASP.NET MVC? To make better understanding of work flow of MVC Routing consider a diagram given below. In above diagram, you can see that when any user make request for any URL, the system check in RouteTable.Routes (Collection of all the Routes). It parses the route and match with current URL. If there are any constraints or attributes are found than it process the constraints and check whether it satisfy than it will Build and
  • 4. 7/16/2014 Understanding Routing in ASP.NET MVC with example http://www.dotnet-stuff.com/tutorials/aspnet-mvc/understanding-routing-in-asp-net-mvc-with-example 4/5 returns RouteData and page will be served , otherwise it will returns null and Page Not Found with Status code 404 can be returned. To understand how Routing is works in MVC at macro level, we have following diagram shows how it is done. The main function of the UrlRoutingModule is to tell the IIS to use IHttpHandler which I got from the matched route. And IIS do the same and returns the result to the browser. Summary: I Hope you have enjoyed this article and now you are able to define routing in ASP.NET MVC application. Although, you need to know something more about attributes in Routing. Thus I have written this in a separate article to understand attributes in Routing in ASP.NET MVC. Keen to here from you...! If you have any questions related to what's mentioned in the article or need help with any issue, ask it, I would love to here from you. Please MakeUseOf Contact and i will be more than happy to help. About the author Anil Sharma is Chief Editor of dotnet-stuff.com. He's a software professional and loves to work with Microsoft .Net. He's usually writes articles about .Net related technologies and here to shares his experiences, personal notes,
  • 5. 7/16/2014 Understanding Routing in ASP.NET MVC with example http://www.dotnet-stuff.com/tutorials/aspnet-mvc/understanding-routing-in-asp-net-mvc-with-example 5/5 Tutorials, Examples, Problems & Solutions, Code Snippets, Reference Manual and Resources with C#, Asp.Net, Linq , Ajax, MVC, Entity Framework, WCF, SQL Server, jQuery, Visual Studio and much more...!!! Connect with the author: • Google + • Linkedin