Problems with MVC routes ASP.Net

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 do not want it 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 them? For backend method calls, I need to pass the action and for page URLs, I omit the action. And, by default, the action called in the page URLs is Index.

    
asked by anonymous 23.02.2017 / 20:20

2 answers

0

I solved with a "gambiarra": I reversed ID with Action in the route, being {controller} / {id} / {action}. So when I make a call on the backend, I always passed the item id (or 0 when I do not have it).

I solved my problem, but I do not think it's the right way to do it.

    
27.02.2017 / 18:55
0

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

It was like this:

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

I wanted it to be like this:

/Admin/Contato/
/Admin/Postagens/

For this I created another route, where only the Controller passed 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 this order to exemplify, but usually you have to add more specific routes first, and then the less specific ones.

    
25.08.2017 / 19:05