Problems with ASP.Net MVC routes

Asked

Viewed 373 times

0

I have a problem with routes in MVC.

routes.MapRoute(
    name: "Default",
    url: "{controller}/{id}",
    defaults: new { controller = "Login", action = "Index", id = UrlParameter.Optional }
);

This route, for my pages, works (because I don’t want you to have an Index in the URL). However, when I need to call a backend method, I need to pass the action.

How can I create the routes to work the way I need to? For backend method calls, I need to pass the action and page URL, omit the action. And by default, the action called in page Urls is Index.

2 answers

0

I solved with a "gambiarra": inverti ID with Action on the route, getting {controller}/{id}/{action}. So when I make a call on the backend, you always pass the item ID (or 0 when I don’t have).

I managed to solve my problem, but I don’t believe it’s the right way to do it.

0

I had the same problem recently, where I wanted to assemble an Admin, and main page of each area, would display the records of that entity.

It was like that:

/Admin/Contato/Listar/
/Admin/Postagens/Listar/

I wish it were so:

/Admin/Contato/
/Admin/Postagens/

For this I created another route, where I only passed the Controller as you did, and a more specific route where I defined the routes with Actions:

routes.MapRoute(
    name: "Listar",
    url: "Admin/{controller}/",
    defaults: new { controller = "Home", action = "Listar"}
);

routes.MapRoute(
    name: "Default",
    url: "Admin/{controller}/{action}/{id}",
    defaults: new { controller = "Login", action = "Index", id = UrlParameter.Optional }
);

I put it in this order to exemplify, but normally you have to add more specific routes first, and then the less specific ones.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.