【问题标题】:MVC route with array of homogeneous parameters具有同质参数数组的 MVC 路由
【发布时间】:2010-10-06 16:14:34
【问题描述】:

我试图为具有同质参数数组的资源创建路由。

网址如下所示: 产品/类别/{categoryId1}/{categoryId2}/.../brand/{brandID1}/{brandID2}/...

并且希望一个动作方法看起来像这样: public ActionResult GetProducts(IList categoryID, ILIsts brandID) {...}

其中类别和品牌是独立的过滤器。

我找到了类似任务的解决方案: ASP.NET MVC 2 Parameter Array

想知道是否没有更漂亮的解决方案可以使用这个原型 public ActionResult GetProducts(IList categoryID)

而不是 public ActionResult myAction(string url)

动作方法

-- 避免拆分字符串和强制转换?

我怎样才能使这个解决方案适合我的情况?

先谢谢大家了!

【问题讨论】:

    标签: asp.net asp.net-mvc-2


    【解决方案1】:

    使用自定义处理程序,就像我在 this answer 中发布的那样。

    可能需要一些调整,但这样的东西应该可以工作:

    public class ProductsRouteHandler : IRouteHandler
    {
        public IHttpHandler GetHttpHandler(RequestContext requestContext)
        {
            IRouteHandler handler = new MvcRouteHandler();
            var vals = requestContext.RouteData.Values;
            vals["categoryID"] = vals["categories"].Split("/");
            vals["brandID"] = vals["brands"].Split("/");
            return handler.GetHttpHandler(requestContext);
        }
    }
    
    // in the route:
    routes.MapRoute(
       "test",
       "products/category/{*categories}/brand/{*brands}",
       new { Controller = "product", Action = "getproducts"}
       ).RouteHandler = new ProductsRouteHandler ();
    

    【讨论】:

    • 感谢您提供好的解决方案!我只是无法注册这样的路线:“products/category/{*categories}/brand/{*brands}”。发生运行时错误:catch-all 参数只能作为路由 URL 的最后一段出现
    • 执行“products/category/{*parameters}”,然后使用 .Split("/brand/") 获得 2 件......然后它几乎已经在里面了 :)跨度>
    • ...根据您的需要,您可能还想添加对参数的约束,以便仅在 /brand/ 存在时才使用路由
    猜你喜欢
    • 2016-03-22
    • 1970-01-01
    • 2017-05-27
    • 2010-09-24
    • 2016-01-22
    • 2017-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多