在MVC多个可选参数不工作 [英] Multiple optional parameters in MVC is not working

查看:158
本文介绍了在MVC多个可选参数不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的要求是向URL提供可选参数。网址应该是这样的。

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/

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

我已经写了下面的路线

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" });


        }

和写的控制器:

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

其工作罚款1 url,但不工作的第二个URL。

推荐答案

您需要定义一个路由的每个组合像下面

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

                 }
);

请参照<一个href=\"http://haacked.com/archive/2011/02/20/routing-regression-with-two-consecutive-optional-url-parameters.aspx/\"相对=nofollow> 路由回归凭借连续两个可选的URL参数

这篇关于在MVC多个可选参数不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆