开发者

Mapping problem of ASP.NET MVC route with optional URL parameter

routes.MapRoute("Archive.CityState",
              "Archive/{City}/{State}/{OP1}/{OP2}",
               new { controller = "Archive", action = "CityState", OP1 = UrlParameter.Optional, OP2 = UrlParameter.Optional },
               new { City="[a-zA-Z]+" ,State = @"[a-zA-Z]{2}", OP1 = @"[a-zA-Z]+" , OP2 =@"\d{4}" });


public ActionResult CityState(string City, string State, string OP1, int OP2)
        {
            var x = City; 
            var y = State;
            var OptionalParameter1= OP1;
            var OptionalParameter2 = OP2;
            return View();
        }

This c开发者_运维百科an map

Archive/Remond/WA/Chemistry

Archive/Remond/WA/Chemistry/2010

But not

Archive/Remond/WA

Can anyone help? Thanks.


These constraints prevent it from matching what you want:

OP1 = @"[a-zA-Z]+", 
OP2 = @"\d{4}"

As both parameters are required. Modify your regular expression to accept empty values if you want this route to be able to be matched by Archive/Remond/WA. Also remember that only the last parameter can be optional (you cannot have two successive optional parameters as this makes no sense).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜