开发者

Mapping action input variables to an array via a route, with constraints

I am trying to map a number of querystring variables into an array that is one of the parameters for an action method.

The action method is as follows:

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

//controlle开发者_开发知识库r logic here

}

We can easily get MVC to bind to the variable generics by using a querystring such as ?generics=test1&generics=test2, however we are looking to set up a route as follows:

/whatever/test1/test2

The following route configuration works:

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

Our issue is that we would like to apply some constraints to the values generics[0] and generics[1], so that they are in the date format 12-12-2009.

We have tried the following, however the constraint does not allow anything through at all:

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

We have tried the following, however this threw a run time error:

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

Please would someone be so good as to let us know if this can be done, and if so, how?

Thanks!

Pat


There's always last resort - 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));
            }
         }

Then just map your route with that constraint =>

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

routes.add("UberRoute", route);

Keep in mind that complex routes can kill you.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜