Frage

I have an ASP.NET MVC 5 website.

Following the suggestion in various blogs, I used T4MVC to change my routing from:

context.MapRoute(
    name:"MyArea_default",
    url:"MyArea/{controller}/{action}/{id}",
    defaults:new { action = "Index", id = UrlParameter.Optional }
);

...to...

context.MapRoute(
    name: "MyArea_default",
    url: "MyArea/{controller}/{action}",
    defaults: MVC.MyArea.Orders.Index()
);

This "worked", but I did wonder about the removal of the {id} segment from the URL pattern. And sure enough, the URLs have changed from (e.g.):

/MyArea/Orders/Edit/1

...to:

/MyArea/Orders/Edit?id=1

I'm really not a fan of the query string parameter, so I'd like to use the previous form.

I tried putting the {id} part back into the route definition:

context.MapRoute(
    name: "MyArea_default",
    url: "MyArea/{controller}/{action}/{id}",
    defaults: MVC.MyArea.Orders.Index()
);

...but of course the defaults no longer provide a default value for id, and so that doesn't work. If the Index action took an optional id parameter, then I'd be able to do this:

context.MapRoute(
    name: "MyArea_default",
    url: "MyArea/{controller}/{action}/{id}",
    defaults: MVC.MyArea.Orders.Index(null) // <- DEFAULT FOR ID
);

...but it doesn't, so I'm stuck.

Also, I'm nervous about the fact that a specific controller is now specified in the route definition. Prior to the T4MVC changes, the route did not specify a controller. Does the new style now mean that I need a route per-controller?

War es hilfreich?

Lösung

You should just look at T4MVC as a typing aid to avoid magic values. Beyond that, everything works the same way, so you're not any more tied to a specific controller than before.

To solve your issue, please try:

defaults: MVC.MyArea.Orders.Index().AddRouteValue("id", UrlParameter.Optional)
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top