ASP.NET MVC自定义可选参数

时间:2015-09-29 18:26:03

标签: c# asp.net asp.net-mvc

如果后者未设置可选参数,如何在ASP.NET MVC 5中定义一个忽略静态前缀/后缀(如"zip-""-county")的路由?

所以在这种情况下例如:

routes.Add("Search",
    new LowercaseDashedRoute(
    "search/{searchType}/{state}/{county}-county/{city}",
    new RouteValueDictionary(new {
        controller = "Home",
        action = "Search",            
        county = UrlParameter.Optional,
        city = UrlParameter.Optional }),
    new RouteValueDictionary(new { searchType = searchTypeConstraint }),
    new LowercaseDashedRouteHandler()));

如果缺少county,则网址会像/search/sale/ca/los-angeles,但不是 /search/sale/ca/-county/los-angeles

2 个答案:

答案 0 :(得分:0)

您可以为您的县参数设置约束,然后在没有它的情况下创建另一个路径:

routes.Add("Search",
    new LowercaseDashedRoute(
    "search/{searchType}/{state}/{county}/{city}",
    new RouteValueDictionary(new {
        controller = "Home",
        action = "Search",            
        county = UrlParameter.Optional,
        city = UrlParameter.Optional }),
    new RouteValueDictionary(new { searchType = searchTypeConstraint, county="\\S+-county" }),
    new LowercaseDashedRouteHandler()));

路线2:

routes.Add("Search",
    new LowercaseDashedRoute(
    "search/{searchType}/{state}/{city}",
    new RouteValueDictionary(new {
        controller = "Home",
        action = "Search",
        city = UrlParameter.Optional }),
    new RouteValueDictionary(new { searchType = searchTypeConstraint }),
    new LowercaseDashedRouteHandler()));

缺点是“-county”后缀将添加到参数中,但您可以在控制器中轻松处理。

答案 1 :(得分:0)

单个路径上不可能有2个可选参数,或者将可选参数与段中的文字部分组合在一起。

但是,为了获得所需的效果,您可以添加另一个路径来处理没有县的情况(并将县删除为可选参数)。

// Matches:
//     /search/sale/ca/los-angeles-county/los-angeles
//     /search/sale/ca/los-angeles-county
routes.Add("SearchCounty",
    new LowercaseDashedRoute(
    "search/{searchType}/{state}/{county}-county/{city}",
    new RouteValueDictionary(new {
        controller = "Home",
        action = "Search",            
        city = UrlParameter.Optional }),
    new RouteValueDictionary(new { searchType = searchTypeConstraint }),
    new LowercaseDashedRouteHandler()));

// Matches:
//     /search/sale/ca/los-angeles
routes.Add("Search",
    new LowercaseDashedRoute(
    "search/{searchType}/{state}/{city}",
    new RouteValueDictionary(new {
        controller = "Home",
        action = "Search" }),
    new RouteValueDictionary(new { searchType = searchTypeConstraint }),
    new LowercaseDashedRouteHandler()));

如果将<something>-county作为第4段传入,则路由引擎将仅匹配第一条路线,因此它将能够区分该情况而不仅仅传递city参数。