Advance Routing in Asp.net MVC

Explained earlier how to use the routing system to handle incoming URLs Fundamentals of Asp.net MVC routing

We also need to be able use our URL schema to generate outgoing URLs we can
embed in our views.

Generating Outgoing URLs in Views:

Generally in MVC application you want to navigate from one view to another view, this can be done by using link of one view and target the action method of other view by setting href property.

<a href=”/Home/GetName “>Redirect to second View</a>

where Home is controller and GetName is method of other view.  

This is quick and simple to create hardcoded URL, but extremely dangerous.  because when you change the URL schema of your application. you need to update all your references which is tedious, error-prone. so a better alternative is to use routing system to generate outgoing URLs dynamically.

  • Routing System to Generate an Outgoing URL:

The simplest way to use mvc html helper method Html.ActionLink to generate URLs based on routing system.

The HTML that the ActionLink method generates based on current route configuration assuming that the request being rendered by a request to home controller.

<a href=”/Home/GetName “>Redirect to second View</a>

which is similar to hardcoded URL as above, but the benefit of this approach is that it automatically responds to changes in the routing configuration.

The new route has changed the url schema, now the HTML that is generated by the ActionLink HTML
helper method, as follows:

<a href=”/App/GetName “>Redirect to second View</a>

changed in routing schema and have changed the outgoing links in our views automatically.

The routing system processes the routes in the order that they were added to the RouteCollection object passed to the RegisterRoutes method. For matching routing Each route is inspected to
see if it is a match, which requires three conditions to be met:

  • A value must be available for every segment variable defined in the URL pattern.
  • None of the values we provided for the segment variables may disagree with the
    default-only variables defined in the route.
  • The values for all of the segment variables must satisfy the route constraints. See
    the “Constraining Routes” section earlier blog Route constraints

the routing system doesn’t try to find best matching route it finds only first match. if there is no matched found it will generate HTML with blank href which cause no redirection.

<a href=” “>Redirect to second View</a>