mvc

Creating Custom Segments in MVC.NET URL Routing

Creating Custom Segments in MVC.NET URL Routing, RouteData.Value,ViewBag , Controllers, Actions, and Variables,regular Controller
Share it:

URL Routing allows you to define your own variables and not just Controllers and Actions. These variables are defined as shown in the code example below:

public static void RegisterRoutes(RouteCollection routes)

        {

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

                new { controller = "Group", action = "List", id = "ProductId" });

        }


We can see that we have our regular Controller and Action defined as Group and List in addition to our Custom variable called ProductId. Moreover, this pattern can match URLs with zero to three segments, and default values can be assigned to all three types of segments: Controllers, Actions, and Variables.

Accessing these custom variables can be done with the help of RouteData.Values property as shown in the example below:
  public ViewResult CustomURLVariable()
        {
             ViewBag.CustomURLVariable = RouteData.Values["id"];
            return View();
        }

We can use ViewBag now in order to retrieve the value from our custom variable and display it on the page.

@{ ViewBag.Title = "CustomURLVariable"; } Variable: @ViewBag.CustomURLVariable

In order to render this Custom Variable, we need to code CustomURLVariable in Group Controller and call http://site.com/Group/CustomURLVariable/Smartphone123 in the URL. However, there is another way of accomplishing the same which is more intuitive but just as effective.


 public ViewResult CustomVariable(string id)

        {

             ViewBag.CustomVariable = id;

            return View();

        }

 
In the example above we are able to pass a variable to our ViewBag without using RouteData.Value[“id”] method. We need to make sure that our parameter for CustomerVariable is an exact match for our segment name and MVC.NET takes care of matching both and passing them through. Moreover, variable conversion happens automatically based on the data type of the method parameter.
Share it:

mvc

Post A Comment:

0 comments: