Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC 5 Routing and Optional Parameters

I have the following controller and route definition

[System.Web.Mvc.Route("users/{firstName?}/{lastName?}/{emailAddress?}/{pageSize:int=10}/{pageNumber:int=1}", Name = RouteNames.User_Listing)]
public ActionResult Index(string firstName = null, string lastName = null, string emailAddress = null, int pageNumber = 1, int pageSize = 10)

What I want is for any of these to be undefined or defined and so all these would be valid

users/first/last/email
users/last/email/30/2
users/last/1
users

Problem is, how does MVC know which of the parameters has been specified? It doesn't!

When I have this link

@Html.RouteLink("Maintain Users", RouteNames.User_Listing)

it doesn't navigate to this action method. What do I do?

like image 528
Sachin Kainth Avatar asked Feb 19 '14 12:02

Sachin Kainth


People also ask

What is routing in MVC 5 with example?

Routing is a pattern matching system. Routing maps an incoming request (from the browser) to particular resources (controller & action method). This means routing provides the functionality to define a URL pattern that will handle the request. That is how the application matches a URI to an action.

How do you send an optional parameter to a route?

You can make a URI parameter as optional by adding a question mark (“?”) to the route parameter. If you make a route parameter as optional then you must specify a default value by using parameter = value for the method parameter.

Can you enable attribute routing in MVC 5?

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. The earlier style of routing, called convention-based routing, is still fully supported.

What is UrlParameter optional?

The UrlParameter is defined as below: // Summary: // Represents an optional parameter that is used by the System.Web.Mvc.MvcHandler // class during routing. public sealed class UrlParameter { // Summary: // Contains the read-only value for the optional parameter.


1 Answers

You just need to specify multiple attributes for this action:

[Route("users/{firstName?}")]
[Route("users/{firstName}/{lastName?}")]
[Route("users/{firstName}/{lastName}/{emailAddress?}")]
...
like image 172
Philipp Munin Avatar answered Oct 24 '22 07:10

Philipp Munin