Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Route constraint asp.net mvc

This is my Route config:

routes.MapRoute(
            name: "AdsCategories",
            url: "Ads/{key}",
            defaults: new { controller = "Ads", action = "Index" },
            //constraints: new { key =  },
            namespaces: new string[] { "Vprok.Controllers" }
        );

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
            namespaces: new string[] { "Vprok.Controllers"}
        );

How to create a constraint "AdsCategories"? I need use default route, if action in controller "Ads" == {key}.

like image 312
Buboon Avatar asked Jan 28 '14 13:01

Buboon


2 Answers

So basically if {key} is an existing action you want it to be handled by the default route instead of using the Index action on the Ads controller?

In order to achieve that you could list all the possible actions in the key constraint:

routes.MapRoute(
    name: "AdsCategories",
    url: "Ads/{key}",
    defaults: new { controller = "Ads", action = "Index" },
    constraints: new { key = @"^create|update|delete" },
    namespaces: new string[] { "Vprok.Controllers" }
);

In this example the AdsCategories route will match only if the url is not ads/create or ads/update or ads/delete. For example ads/foobar will match.

like image 163
Darin Dimitrov Avatar answered Sep 18 '22 13:09

Darin Dimitrov


take the following code out:

routes.MapRoute(
            name: "AdsCategories",
            url: "Ads/{key}",
            defaults: new { controller = "Ads", action = "Index" },
            //constraints: new { key =  },
            namespaces: new string[] { "Vprok.Controllers" }
        );

just create an index actionresult on ads controller and add a id parameter to it! DONE

like image 26
JC Lizard Avatar answered Sep 21 '22 13:09

JC Lizard