Multiple optional parameters in MVC is not working

空扰寡人 提交于 2019-12-11 18:57:20

问题


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



来源:https://stackoverflow.com/questions/22507476/multiple-optional-parameters-in-mvc-is-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!