Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Routing with and without controller name in ASP.NET MVC 4

I'm using ASP.NET MVC 4 and I have some problems settings up my routes. Could you tell my how to set up my routes to point urls to actions as follows:

  • "/" (or "/Start") => PublicController.Start()
  • "/About" => PublicController.About()
  • "/MyPage" (or "/MyPage/Summary") => MyPageController.Summary()
  • "/MyPage/Invoices" => MyPageController.Invoices()
  • "/MyPage/Invoice/72" => MyPageController.Invoice(int id)

It's the url "/About" that messes things up for me, i.e. a url that does not specify the controller. If I make that one work the others that do specify controller stop working. I could just create a separate controller for "/About" I guess, but I'd rather not if I don't have to (I have more urls following that pattern).

like image 855
haagel Avatar asked Apr 05 '13 14:04

haagel


People also ask

How can use route in MVC controller?

Configure a Route Every MVC application must configure (register) at least one route configured by the MVC framework by default. You can register a route in RouteConfig class, which is in RouteConfig. cs under App_Start folder. The following figure illustrates how to configure a route in the RouteConfig class .

What is default routing in MVC?

The Default route maps the first segment of a URL to a controller name, the second segment of a URL to a controller action, and the third segment to a parameter named id. The Default route maps this URL to the following parameters: controller = Home. action = Index.

What is difference between attribute and conventional routing?

As per our opinion, Attribute Routing provides us more flexibilities as compared to Convention Based Routing. In Attribute Routing, we can manage route as controller level, action level and also area level. Also, it can override the child route, if required.

How many types of routing are there in MVC?

MVC 5 supports a new type of routing, called attribute routing. As the name implies, attribute routing uses attributes to define routes. Attribute routing gives you more control over the URIs in your web application. The earlier style of routing, called convention-based routing, is still fully supported.


1 Answers

This should do it:

routes.MapRoute(
    name: "About",
    url: "About",
    defaults: new { controller = "Public", action = "About" }
);

routes.MapRoute(
    name: "MyPageSummary",
    url: "MyPage",
    defaults: new { controller = "MyPage", action = "Summary" }
);

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Public", action = "Start", id = UrlParameter.Optional }
);
like image 171
Darin Dimitrov Avatar answered Sep 22 '22 19:09

Darin Dimitrov