Sunday, December 4, 2016

MVC Routing

Routing
Define URL structure and map the URL with the controller.

E.g. user types “http://localhost/View/ViewCustomer/”, it goes to the “Customer” Controller and invokes the DisplayCustomer action.
This is defined by adding an entry in to the routes collection using the maproute function.

routes.MapRoute(
               "View", // Route name
               "View/ViewCustomer/{id}", // URL with parameters
               new { controller = "Customer", action = "DisplayCustomer", 
id = UrlParameter.Optional }); // Parameter defaults   

Route Mapping is writte in "RouteConfig.cs" and register using "global.asax" application start event.

you can map mutiple URL with same action. Just need to make 2 entry with different key name and specify the same controller and action.

MVC 5, by using the "Route" attribute we can define the URL structure.
E.g. in the below code we have decorated the "GotoAbout" action with the route attribute. The route attribute says that the "GotoAbout" can be invoked using the URL structure "Users/about".

public class HomeController : Controller
{
       [Route("Users/about")]
       public ActionResult GotoAbout()
       {
           return View();
       }
}

Advantage of define Route Structure (MVC5)

Developers can see the URL structure in top of the method rather than go to “routeconfig.cs” and see the lengthy codes.
This is much user friendly as compared to scrolling through the “routeconfig.cs” file and going through the length line of code to figure out which URL structure is mapped to which action.

public class HomeController : Controller
{
       [Route("Users/about")]
       [Route("Users/WhoareWe")]
       [Route("Users/OurTeam")]
       [Route("Users/aboutCompany")]
       public ActionResult GotoAbout()
       {
           return View();
       }
}

No comments:

Post a Comment