mvc

Optional MVC.NET URL Segments - UrlParameter.Optional

Optional MVC.NET URL Segments - UrlParameter.Optional, MVC.NET URL Routing,Mvc.NET,UrlParameter.Optional
Share it:
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 it:

mvc

Post A Comment:

0 comments: