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?
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.
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.
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.
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.
You just need to specify multiple attributes for this action:
[Route("users/{firstName?}")]
[Route("users/{firstName}/{lastName?}")]
[Route("users/{firstName}/{lastName}/{emailAddress?}")]
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With