Wahyu Wahyudi
Wahyu Wahyudi

Reputation: 53

ASP .Net MVC Routing without Controller and Action Name

simple question. I want something like:

http:/ /www.mywebsite.com/microsoft or http:/ /www .mywebsite.com/apple so microsoft and apple should be like id but i use it just like controller in the default

this is the default route

routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Home", action = "index", id = UrlParameter.Optional } // Parameter defaults
        );

This produce something like http:/ /www.mywebsite .com/home/aboutus or http: //www.mywebsite .com/products/detail/10

I added another route

routes.MapRoute(
            "Partner", // Route name
            "{id}", // URL with parameters
            new { controller = "Home", action = "Partners"}, // Parameter defaults
            new { id = @"\d+" }
        );

but this has constraint that only allow numeric id.

how do I accomplish what I wanted.

thanks

Upvotes: 3

Views: 3318

Answers (3)

Jon
Jon

Reputation: 16718

If you don't want to provide a numeric constraint, just delete the 4th parameter, ie

routes.MapRoute("Partner", "{id}", new { controller = "Home", action = "Partners"});

The 4th parameter is an anonymous object that provides constraints for the route parameters that you have defined. The names of the anonymous object members correspond to the route parameters - in this case "controller" or "action" or "id", and the values of these members are regular expressions that constrain the values that the parameters must have in order to match the route. "\d+" means that the id value must consist of one or more digits (only).

Upvotes: 0

Richard
Richard

Reputation: 22016

Not sure exactly what you are trying to achieve but it looks like you need a custom route constraint. Take a look here for an example:

http://blogs.planetcloud.co.uk/mygreatdiscovery/post/Custom-route-constraint-to-validate-against-a-list.aspx

Remember to register the route constraint first

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

If the expression can contain only letters and digits you could modify the constraint:

routes.MapRoute(
    "Partner", // Route name
    "{id}", // URL with parameters
    new { controller = "Home", action = "Partners"}, // Parameter defaults
    new { id = @"^[a-zA-Z0-9]+$" }
);

Upvotes: 4

Related Questions