【问题标题】:how to use t4mvc routing helper with custom route constraints如何使用带有自定义路由约束的 t4mvc 路由助手
【发布时间】:2011-08-13 16:25:48
【问题描述】:

我在当前项目中使用 t4mvc 并尝试使用包含的路由助手但是当我尝试使用如下自定义约束时

     routes.MapRoute(
        "def_filtered_reports_route",
        "reports/{samplePoint}/{fromDate}/{toDate}",
        MVC.Report.Results(null, null, null),
        new
        {
            samplePoint = new SamplePointExistsConstraint(),
            fromDate = new DateTimeConstraint(),
            toDate = new DateTimeConstraint()
        }
        );

它抛出一个ArgumentException 声明An item with the same key has already been added.

如果我这样写

 routes.MapRoute(
    "def_filtered_reports_route",
    "reports/{samplePoint}/{fromDate}/{toDate}",
    MVC.Report.Results(null, null, null) );

或者像这样

    routes.MapRoute(
           "def_filtered_reports_route",
           "reports/{samplePoint}/{fromDate}/{toDate}",
           new
           {
               controller = "Report",
               action = "Results",
               fromDate = "",
               toDate = "",
               samplePoint = ""
           },
           new
           {
               fromDate = new DateTimeConstraint(),
               toDate = new DateTimeConstraint(),
               samplePoint = new SamplePointExistsConstraint()
           });

它工作正常。

是我遗漏了什么还是 t4mvc 不支持自定义约束

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-3 t4mvc


    【解决方案1】:

    尝试在约束之前为默认值传递一个额外的 null。例如

            routes.MapRoute(
               "def_filtered_reports_route",
               "reports/{samplePoint}/{fromDate}/{toDate}",
               MVC.Report.Results(null, null, null),
               null /*defaults*/,
               new {
                   samplePoint = new SamplePointExistsConstraint(),
                   fromDate = new DateTimeConstraint(),
                   toDate = new DateTimeConstraint()
               }
               );
    

    【讨论】:

    • 如果我使用助手,我是否还需要在匿名对象中使用默认值定义控制器和动作,或者助手是否仅在动作被删除时中断
    • 如果你使用帮助器,那么传递 MVC.Report.Results(...) 确实消除了在默认匿名对象中传递控制器/动作的需要。
    • 所以只需通过帮助程序传递您的默认值,然后将 null 扔到默认方式,听起来不错,谢谢大卫
    猜你喜欢
    • 1970-01-01
    • 2016-07-17
    • 1970-01-01
    • 2020-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多