Multiple optional parameters in MVC is not working

2019-09-10 13:15发布

问题:

My requirement is to provide optional parameters to urls. urls should be like the.

  1. http://test.com/118939
  2. http://test.com/118939/test/2000/

I have written following routes

public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.IgnoreRoute("{*favicon}", new { favicon = @"(.*/)?favicon.ico(/.*)?" });

            routes.MapRoute(
                "FAQDefault",
                "FAQ",
                new { controller = "FAQ", action = "Default" });
            routes.MapRoute(null, "{id}", new { controller = "Home", action = "Default", id = UrlParameter.Optional });
            routes.MapRoute("rent", "{id}/{rent}/{unit}", new { controller = "Home", action = "Default", id = UrlParameter.Optional, rent = UrlParameter.Optional, unit = UrlParameter.Optional });
            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { controller = "Home", action = "Default", id = UrlParameter.Optional }, // Parameter defaults
                new string[] { "CDCPortal" });


        }

and controller written like:

 public ActionResult Default(string id, string rent=null,string unit=null){}

Its working fine for 1 url but not working for second url.

回答1:

There is no need to do as, you have done in the first case:

The second route can handle any number of parameters.



回答2:

You need to define a route for each combinations like below

routes.MapRoute("Default-AllOptional", 
                "Default/{id}/{rent}/{unit}", 
                 new
                 {
                     controller = "Home",
                     action = "Default"
                     // nothing optional 
                 }
);

routes.MapRoute("Defaul-Id-rent-Optional", 
                "Default/{id}/{rent}", 
                 new
                 {
                     controller = "Home",
                     action = "Default",
                     id=UrlParameter.Optional,
                     rent=UrlParameter.Optional

                 }
);

Refer Routing Regression With Two Consecutive Optional Url Parameters