Parameters in the URL using /

Asked

Viewed 35 times

2

I need to have a URL in the following format:

nomedosite.com/note/{anything}

I need this URL to trigger the controller Note, with the action Index. How should I set my route?

I tried to use this:

routes.MapRoute(
            name: "OpenNote",
            url: "{controller}/{*stringNote}",
            defaults: new { controller = "Note", action = "Index", stringNote = UrlParameter.Optional }
        );

but I always get page 404, IE, it is not working as I want. How should I configure my route?

  • That one anything is going to be a string passed? because it has a asterisk?

  • yes it is a string, it has asterisk because it was in the tutorial that followed, but I tried it without it and also did not give

1 answer

1


When I need to mount routes with a parameter I only do it as follows:

Instead of leaving the controller dynamic I already force the route of the controller, also add constraints to accept only letters

routes.MapRoute(
           name: "OpenNote",
           url: "Note/{stringNote}",
           defaults: new { controller = "Note", action = "Index" },
           constraints: new { stringNote= @"[aA-zZ]" }
       );

A very important point is that custom routes should always come before the default route because he always "hits" on the first route he gets

routes.MapRoute(
           name: "OpenNote",
           url: "Note/{stringNote}",
           defaults: new { controller = "Note", action = "Index" },
           constraints: new { stringNote= @"[aA-zZ]" }
       );


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

    "should always come before the default route" was that! after this I will take a course in mvc xD

Browser other questions tagged

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