2010-01-29 54 views
1

我想將一些查詢字符串變量映射到作爲操作方法參數之一的數組中。通過路由將動作輸入變量映射到數組,帶有約束

的操作方法如下:

public ActionResult Index(string url, string[] generics) 
{ 

//controller logic here 

} 

我們可以很容易地得到MVC綁定到變量仿製藥使用的查詢字符串,例如泛型= test1的&泛型= test2的,但是我們正在設置?一個路線如下:

/不管/ TEST1/test2的

下面的路由配置工作:

routes.MapRoute(
      "TestRoute", 
      "whatever/{generics[0]}/{generics[1]}", 
      new { controller = "Main", action = "Index" }} 
     ); 

我們的問題是,我們想對泛型[0]和泛型[1]的值應用一些約束,以便它們的日期格式爲12-12-2009。

我們曾嘗試以下,但該約束不通過在所有允許任何東西:

routes.MapRoute(
      "TestRoute", 
      "whatever/{generics[0]}/{generics[1]}", 
      new { controller = "Main", action = "Index" }}, 
      new { generics = @"[0-9]{2}\-[0-9]{2}\-[0-9]{2,4}" } 
     ); 

我們曾嘗試以下,但是這投擲了運行時錯誤:

routes.MapRoute(
    "TestRoute", 
    "whatever/{generics[0]}/{generics[1]}", 
    new { controller = "Main", action = "Index" }}, 
    new { generics = new string[2]{ @"[0-9]{2}\-[0-9]{2}\-[0-9]{2,4}",@"[0-9]{2}\-[0-9]{2}\-[0-9]{2,4}"}} 
); 

請有人會如此高興地告訴我們這是否可以完成,如果可以,怎麼做?

謝謝!

帕特

回答

2

總有最後一招 - IRouteConstraint =>

public class GenericsConstraint : IRouteConstraint 
     { 
      public bool Match(HttpContextBase httpContext, Route route, 
       string parameterName, RouteValueDictionary values, 
       RouteDirection routeDirection) 
      { 
       //not sure if that will cast 
       var generics = values["generics"] as string[]; 

       var rgx = new Regex("tralala"); 

       // not not... hahahaha 
       return !generics.Any(x=>!rgx.Match(x)); 
      } 
     } 

然後,只需與約束=>

var route = new Route("whatever/{generics[0]}/{generics[1]}", 
            new MvcRouteHandler()) 
     {Constraints = new RouteValueDictionary(new GenericsConstraint())}; 

routes.add("UberRoute", route); 

映射你的路線請記住,complex routes can kill you

+0

感謝您的回覆Arnis,我會看看這種方法。 – 2010-01-29 15:06:19