It is possible to generate routes dynamically in ASP.NET MVC4

Asked

Viewed 61 times

0

I am fixing some URL’s of my site and need to create several different routes for each page, for example:

routes.MapRoute(
    name: "ComoVenderMinhasImagens",
    url: "como-vender-minhas-imagens",
    defaults: new { controller = "Home", action = "ComoVenderMinhasImagens", id = UrlParameter.Optional }
);
routes.MapRoute(
    name: "PerguntasFrequentes",
    url: "perguntas-frequentes",
    defaults: new { controller = "Home", action = "PerguntasFrequentes", id = UrlParameter.Optional }
);
routes.MapRoute(
    name: "FormasdePagamento",
    url: "formas-de-pagamento",
    defaults: new { controller = "Home", action = "FormasdePagamento", id = UrlParameter.Optional }
);
routes.MapRoute(
    name: "BancoDeImagens",
    url: "banco-de-imagens",
    defaults: new { controller = "Home", action = "BancoDeImagens", id = UrlParameter.Optional }
);

As in the example, I need to create URL’s in which words are separated by - in some cases, there is some framework tool that allows me to create a generic route that works for any type of Action whatever the number of words?

(Stock-of-images && how-to-sell-my-images && Frequently Asked Questions && Questions)

  • You wanted a route that received in the url any set of words separated by - and forwarded to action that in the name does not contain the - ?

  • That, or the other way around, he was named after Action FormasDePagamento and automatically separate maybe through the upper case and put the -

  • Because I can’t put public Actionresult forms-of-payment then I would need to put Formasdepaming and route automatically separate

  • 1

    An option would be to annotate actions with the attribute [Route("name-of-your-route")], this suits you ?

1 answer

0


in your controller you only need to put the route:

public class HomeController : Controller
{
   [Route("")]
   [Route("Home")]
   [Route("Home/Index-EXEMPLO")]
   public IActionResult Index()
   {
      return View();
   }
   [Route("Home/About-EXEMPLO")]
   public IActionResult About()
   {
      return View();
   }
   [Route("Home/Contact-EXEMPLO")]
   public IActionResult Contact()
   {
      return View();
   }
}

if you still have doubt on the Microsoft website explains about this: TUTORIAL

  • Thanks Hudson, I will test your answer and see if it meets... ai mark as ok . I will also see if I can put parameters inside this Route... then I edit the answer to leave more complete.

  • @Leonardobonetti parameters will look like this "Home/Contact-EXAMPLE/{var1}/{var2}"

Browser other questions tagged

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