SlideShare une entreprise Scribd logo
1  sur  6
Télécharger pour lire hors ligne
7/16/2014 Attributes in Routing in ASP.NET MVC with example:
http://www.dotnet-stuff.com/tutorials/aspnet-mvc/attributes-in-routing-in-asp-net-mvc-with-example 1/6
R
Attributes in 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, Attributes in Routing, Routing Attributes, MVC Routing Attributes, Routing
Attributes Example
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.
You can find more details about ASP.NET MVC Routing in separate articles. Here, I am going to discuss about
Attributes in Routing in ASP.NET MVC.Now, you are able to know what following code says.
Here, we have defined a route for the application. When the route definitions are co-located with the actions, within
the same source file rather than being declared on an external configuration class, it can make it easier to reason
about the mapping between URIs and actions. The previous route definition would be set using the following, simple
attribute:
How to Enable Attribute Routing
 


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);
}
1
2
[Route("{categoryId:int}/{categoryTitle}")]
publicActionResultShow(intcategoryId){...}
7/16/2014 Attributes in Routing in ASP.NET MVC with example:
http://www.dotnet-stuff.com/tutorials/aspnet-mvc/attributes-in-routing-in-asp-net-mvc-with-example 2/6
It is very easy to enable Attribute in Routing,You just need to call MapMvcAttributeRoutes during configuration.
Following is an example to enable attribute in Routing.
Attribute Routing in ASP.NET MVC Example
After Enabling the attributes in application you can define a route attribute on top of an action method. The following
is the example of a Route Attribute in which routing is defined where the action method is defined. In the following
example, I am defining the “Route” attribute on top of the action method.
Attribute Routing with Optional Parameter
It is possible that we may have the requirement for something that must accept some options parameter. We can
define an optional parameter in the URL pattern by defining a question mark (“?") to the route parameter. We can
also define the default value by using parameter=value.
1
2
3
4
5
6
7
8
9
10
publicstaticvoidRegisterRoutes(RouteCollectionroutes)
{
routes.MapMvcAttributeRoutes();
routes.MapPageRoute("",
"Category/{action}/{categoryName}",
"~/categories.aspx",
true,
newRouteValueDictionary
{{"categoryName","MVC"},{"action","show"}});
}
1
2
3
4
5
6
7
8
9
publicclassHomeController:Controller
{
//URL:/Category
[Route("Category")]
publicActionResultIndex(){
ViewBag.Message="WelcometoASP.NETMVCRouting!";
returnView();
}
}
1
2
3
4
publicclassHomeController:Controller
{
//OptionalURIParameter
7/16/2014 Attributes in Routing in ASP.NET MVC with example:
http://www.dotnet-stuff.com/tutorials/aspnet-mvc/attributes-in-routing-in-asp-net-mvc-with-example 3/6
Route Prefixes in Routing in ASP.NET MVC
Sometimes, we may got the requirements which include some prefix in the entire Action Methods. We can also set a
common prefix for the entire controller (all action methods within the controller) using the “RoutePrefix” attribute.
Following is an example shows how we can define Route Prefix.
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
//URL:/Category/
//URL:/Category/MVC
[Route("Category/{categoryName?}")]
publicActionResultShow(stringcategoryName){
ViewBag.Message="ThisisAttributeRoutingwithOptionalParameterASP.NETMVC!";
returnView();
}
//OptionalURIParameterwithdefaultvalue
//URL:/Category/
//URL:/Category/MVC
[Route("Category/{categoryName="MVC"}")]
publicActionResultShow(stringcategoryName){
ViewBag.Message="ThisisAttributeRoutingwithDefaultValueASP.NETMVC!";
returnView();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
[RoutePrefix("Category")]
publicclassHomeController:Controller
{
//URL:/Category/
[Route]
publicActionResultIndex()
{
ViewBag.Message="WelcometoDotNetStuff!";
returnView();
}
//OptionalURIParameter
//URL:/Category/
//URL:/Category/MVC
[Route("{categoryName}")]
publicActionResultShow(stringcategoryName)
{
ViewBag.Message="WelcometoASP.NETMVCCategory!";
returnView();
}
}
7/16/2014 Attributes in Routing in ASP.NET MVC with example:
http://www.dotnet-stuff.com/tutorials/aspnet-mvc/attributes-in-routing-in-asp-net-mvc-with-example 4/6
If we want to override the route prefix, we should use a tide (~) sign with the Route attribute. Following is an example
which shows how it can be done.
Defining Default Route using Route Attribute in ASP.NET
MVC Routing
If we want to define default route for any controller, We can do it by defining a Route attribute on top of the
controller, to capture the default action method as the parameter. Following example shows how it can be done.
20
1
2
3
4
5
6
7
8
9
10
11
[RoutePrefix("Category")]
publicclassHomeController:Controller
{
//URL:/OverideRoutePrefix/
[Route("~/NewCategory")]
publicActionResultIndex()
{
ViewBag.Message="Overridetherouteprefix!";
returnView();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
[RoutePrefix("Category")]
[Route("action=index")]
publicclassHomeController:Controller
{
//URL:/Category/
publicActionResultIndex()
{
ViewBag.Message="WelcometoASP.NETMVCRouting!";
returnView();
}
//URL:/Category/NewCategory
publicActionResultNewIndex()
{
ViewBag.Message="ThisisnewCategoryforASP.NETMVC!";
returnView();
}
}
7/16/2014 Attributes in Routing in ASP.NET MVC with example:
http://www.dotnet-stuff.com/tutorials/aspnet-mvc/attributes-in-routing-in-asp-net-mvc-with-example 5/6
Defining Route name in ASP.NET MVC
To define route name in ASP.NET MVC Routing. We can also define a name of the route to allow easy URI
generation. Following example show how to do that.
And to generate URI from above definition of Routing. We can generate URI using Url.RouteUrl method.
Defining Area in ASP.NET MVC Routing
Areas are logical grouping of Controller, Models and Views and other related folders for a module in MVC
applications. By convention, a top Areas folder can contain multiple areas. Using areas, we can write more
maintainable code for an application cleanly separated according to the modules.
If we have Areas in our application, than we can define the "Area" name from the controller that belongs to the using
RouteArea attribute. If we define the “RouteArea” attribute on top of the controller, we can remove the
AreaRegistration class from global.asax. Following is an example to shows how to defining Area in Asp.NET MVC
Routing.
1
2
3
4
5
6
[Route("Category", Name="CategoryURL")]
publicActionResultIndex()
{
ViewBag.Message="WelcometoASP.NETMVCRouting!";
returnView();
}
1 <ahref="@Url.RouteUrl("category")"="">CategoryURI</a>
1
2
3
4
5
6
7
8
9
10
11
12
[RouteArea("PostArea")]
[RoutePrefix("Category")]
[Route("action=index")]
publicclassHomeController:Controller
{
//URL:/PostArea/Category/
publicActionResultIndex()
{
ViewBag.Message="WelcometoASP.NETMVCRouting!";
returnView();
}
}
7/16/2014 Attributes in Routing in ASP.NET MVC with example:
http://www.dotnet-stuff.com/tutorials/aspnet-mvc/attributes-in-routing-in-asp-net-mvc-with-example 6/6
Summary:We can define Routing in a separate file but using Attribute Routing allows us more control over the URIs
in our MVC web application. The earlier way of routing (convention-based routing) is fully supported by this version
of MVC. We can also use both type of routing in the same project. To know convention-based routing you can find it
in a separate article.
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,
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

Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
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
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesZilliz
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
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
 
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
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
"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
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 

Dernier (20)

Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
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
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector Databases
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
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
 
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
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
"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
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 

En vedette

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)

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
 
More than Just Lines on a Map: Best Practices for U.S Bike Routes
More than Just Lines on a Map: Best Practices for U.S Bike RoutesMore than Just Lines on a Map: Best Practices for U.S Bike Routes
More than Just Lines on a Map: Best Practices for U.S Bike Routes
 

Attributes in Routing in ASP.NET MVC with example:

  • 1. 7/16/2014 Attributes in Routing in ASP.NET MVC with example: http://www.dotnet-stuff.com/tutorials/aspnet-mvc/attributes-in-routing-in-asp-net-mvc-with-example 1/6 R Attributes in 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, Attributes in Routing, Routing Attributes, MVC Routing Attributes, Routing Attributes Example 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. You can find more details about ASP.NET MVC Routing in separate articles. Here, I am going to discuss about Attributes in Routing in ASP.NET MVC.Now, you are able to know what following code says. Here, we have defined a route for the application. When the route definitions are co-located with the actions, within the same source file rather than being declared on an external configuration class, it can make it easier to reason about the mapping between URIs and actions. The previous route definition would be set using the following, simple attribute: How to Enable Attribute Routing     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); } 1 2 [Route("{categoryId:int}/{categoryTitle}")] publicActionResultShow(intcategoryId){...}
  • 2. 7/16/2014 Attributes in Routing in ASP.NET MVC with example: http://www.dotnet-stuff.com/tutorials/aspnet-mvc/attributes-in-routing-in-asp-net-mvc-with-example 2/6 It is very easy to enable Attribute in Routing,You just need to call MapMvcAttributeRoutes during configuration. Following is an example to enable attribute in Routing. Attribute Routing in ASP.NET MVC Example After Enabling the attributes in application you can define a route attribute on top of an action method. The following is the example of a Route Attribute in which routing is defined where the action method is defined. In the following example, I am defining the “Route” attribute on top of the action method. Attribute Routing with Optional Parameter It is possible that we may have the requirement for something that must accept some options parameter. We can define an optional parameter in the URL pattern by defining a question mark (“?") to the route parameter. We can also define the default value by using parameter=value. 1 2 3 4 5 6 7 8 9 10 publicstaticvoidRegisterRoutes(RouteCollectionroutes) { routes.MapMvcAttributeRoutes(); routes.MapPageRoute("", "Category/{action}/{categoryName}", "~/categories.aspx", true, newRouteValueDictionary {{"categoryName","MVC"},{"action","show"}}); } 1 2 3 4 5 6 7 8 9 publicclassHomeController:Controller { //URL:/Category [Route("Category")] publicActionResultIndex(){ ViewBag.Message="WelcometoASP.NETMVCRouting!"; returnView(); } } 1 2 3 4 publicclassHomeController:Controller { //OptionalURIParameter
  • 3. 7/16/2014 Attributes in Routing in ASP.NET MVC with example: http://www.dotnet-stuff.com/tutorials/aspnet-mvc/attributes-in-routing-in-asp-net-mvc-with-example 3/6 Route Prefixes in Routing in ASP.NET MVC Sometimes, we may got the requirements which include some prefix in the entire Action Methods. We can also set a common prefix for the entire controller (all action methods within the controller) using the “RoutePrefix” attribute. Following is an example shows how we can define Route Prefix. 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 //URL:/Category/ //URL:/Category/MVC [Route("Category/{categoryName?}")] publicActionResultShow(stringcategoryName){ ViewBag.Message="ThisisAttributeRoutingwithOptionalParameterASP.NETMVC!"; returnView(); } //OptionalURIParameterwithdefaultvalue //URL:/Category/ //URL:/Category/MVC [Route("Category/{categoryName="MVC"}")] publicActionResultShow(stringcategoryName){ ViewBag.Message="ThisisAttributeRoutingwithDefaultValueASP.NETMVC!"; returnView(); } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 [RoutePrefix("Category")] publicclassHomeController:Controller { //URL:/Category/ [Route] publicActionResultIndex() { ViewBag.Message="WelcometoDotNetStuff!"; returnView(); } //OptionalURIParameter //URL:/Category/ //URL:/Category/MVC [Route("{categoryName}")] publicActionResultShow(stringcategoryName) { ViewBag.Message="WelcometoASP.NETMVCCategory!"; returnView(); } }
  • 4. 7/16/2014 Attributes in Routing in ASP.NET MVC with example: http://www.dotnet-stuff.com/tutorials/aspnet-mvc/attributes-in-routing-in-asp-net-mvc-with-example 4/6 If we want to override the route prefix, we should use a tide (~) sign with the Route attribute. Following is an example which shows how it can be done. Defining Default Route using Route Attribute in ASP.NET MVC Routing If we want to define default route for any controller, We can do it by defining a Route attribute on top of the controller, to capture the default action method as the parameter. Following example shows how it can be done. 20 1 2 3 4 5 6 7 8 9 10 11 [RoutePrefix("Category")] publicclassHomeController:Controller { //URL:/OverideRoutePrefix/ [Route("~/NewCategory")] publicActionResultIndex() { ViewBag.Message="Overridetherouteprefix!"; returnView(); } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 [RoutePrefix("Category")] [Route("action=index")] publicclassHomeController:Controller { //URL:/Category/ publicActionResultIndex() { ViewBag.Message="WelcometoASP.NETMVCRouting!"; returnView(); } //URL:/Category/NewCategory publicActionResultNewIndex() { ViewBag.Message="ThisisnewCategoryforASP.NETMVC!"; returnView(); } }
  • 5. 7/16/2014 Attributes in Routing in ASP.NET MVC with example: http://www.dotnet-stuff.com/tutorials/aspnet-mvc/attributes-in-routing-in-asp-net-mvc-with-example 5/6 Defining Route name in ASP.NET MVC To define route name in ASP.NET MVC Routing. We can also define a name of the route to allow easy URI generation. Following example show how to do that. And to generate URI from above definition of Routing. We can generate URI using Url.RouteUrl method. Defining Area in ASP.NET MVC Routing Areas are logical grouping of Controller, Models and Views and other related folders for a module in MVC applications. By convention, a top Areas folder can contain multiple areas. Using areas, we can write more maintainable code for an application cleanly separated according to the modules. If we have Areas in our application, than we can define the "Area" name from the controller that belongs to the using RouteArea attribute. If we define the “RouteArea” attribute on top of the controller, we can remove the AreaRegistration class from global.asax. Following is an example to shows how to defining Area in Asp.NET MVC Routing. 1 2 3 4 5 6 [Route("Category", Name="CategoryURL")] publicActionResultIndex() { ViewBag.Message="WelcometoASP.NETMVCRouting!"; returnView(); } 1 <ahref="@Url.RouteUrl("category")"="">CategoryURI</a> 1 2 3 4 5 6 7 8 9 10 11 12 [RouteArea("PostArea")] [RoutePrefix("Category")] [Route("action=index")] publicclassHomeController:Controller { //URL:/PostArea/Category/ publicActionResultIndex() { ViewBag.Message="WelcometoASP.NETMVCRouting!"; returnView(); } }
  • 6. 7/16/2014 Attributes in Routing in ASP.NET MVC with example: http://www.dotnet-stuff.com/tutorials/aspnet-mvc/attributes-in-routing-in-asp-net-mvc-with-example 6/6 Summary:We can define Routing in a separate file but using Attribute Routing allows us more control over the URIs in our MVC web application. The earlier way of routing (convention-based routing) is fully supported by this version of MVC. We can also use both type of routing in the same project. To know convention-based routing you can find it in a separate article. 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, 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