AdBlock Detected

We provide high-quality source code for free. Please consider disabling your AdBlocker to support our work.

Buy me a Coffee

Saved Tutorials

No saved posts yet.

Press Enter to see all results

Optional MVC.NET URL Segments - UrlParameter.Optional

By pushpam abhishek
Listen to this article
Optional MVC.NET URL Segments - UrlParameter.Optional


MVC.NET URL Routing is designed to handle optional segments. It uses UrlParameter.Optional attribute to achieve this functionality as shown in the Mvc.NET code below:


public static void RegisterRoutes(RouteCollection routes)

        {

            routes.MapRoute("MyURLRoute", "{controller}/{action}/{id}",

                new { controller = "Group", action = "List", id = UrlParameter.Optional });

        }


This setting for your URL route will match URLs with or without the “id” segment that is present in the URL. It will match zero to 3 segments and will fail if there is the fourth segment is present.


URLparameter. Optional ignores the completely “id” segment rather than setting it to null. This way we can see if the user intended to use this “id” segment or now. Contrary to this method, if we were to set up default value as null, then we don’t truly aware of the user’s intentions.

However, URL Route is a powerful tool for handling URLs with segments longer than what we can possibly handle with our Rules. The catchall is used just for this particular purpose. It is designed to handle segments longer as explained in the example above. In fact, it handles an unlimited number of segment

public static void RegisterRoutes(RouteCollection routes)

        {

            routes.MapRoute("MyURLRoute", "{controller}/{action}/{id}/{*catchall}",

                new { controller = "Group", action = "List", id = UrlParameter.Optional });

        }


If your URL has more than 3 segments like it is displayed here:
http://site.com/group/list/id/subid/subsubid
then *catchcall will be set to catchcall=subid/subsubid, and it is up to us to decide what to do with it and how to handle “subid/subsubid” string in our code.


Read More:-

Share this post

pushpam abhishek

About pushpam abhishek

Pushpam Abhishek is a Software & web developer and designer who specializes in back-end as well as front-end development. If you'd like to connect with him, follow him on Twitter as @pushpambhshk

Comments