MVC5属性路由,为没有可选参数的路由发出空值

时间:2014-03-13 11:49:12

标签: asp.net-mvc asp.net-mvc-5 t4mvc attributerouting asp.net-mvc-5.1

我在控制器上:

  

[RoutePrefix("&#34)]

路线的行动:

   [Route("things-to-do/{filter1?}/{filter2?}/{filter3?}/{filter4?}/{Area?}", Name = "thingstodo")]
   public async virtual Task<ActionResult> ThingsToDo(string filter1 = "", string filter2 = "", string filter3 = "", string filter4 = "", string q = "")

如果我在浏览器中输入这些网址,这是有效的:

  

本地主机/事物-待办事项
  本地主机/事到-DO /东西
  本地主机/事到-DO /事/东西

但是这些都返回null:

Url.RouteUrl("thingstodo")  
Url.Action("ThingsToDo", "ControllerName")  
Url.Action(MVC.ControllerName.ThingsToDo())  

这些返回正确的网址:

Url.Action(&#34; ThingsToDo&#34;,&#34; ControllerName&#34;,new {filter1 =&#34;某事&#34;,filter2 =&#34;某事&#34;})
Url.Action(MVC.ControllerName.ThingsToDo(&#34;某事&#34;,&#34;某事&#34;))

如果我不需要可选的参数,如何正确生成网址的任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:3)

我找到了一个可能的解决方案:

    [Route("things-to-do/{filter1}/{filter2}/{filter3}/{filter4}/{Area?}", Order = 1)]
    [Route("things-to-do/{filter1}/{filter2}/{filter3}/{Area?}", Order = 2)]
    [Route("things-to-do/{filter1}/{filter2}/{Area?}", Order = 3)]
    [Route("things-to-do/{filter1}/{Area?}", Order = 4)]
    [Route("things-to-do/{Area?}", Order = 5)]