可选的路由参数和操作选择

时间:2011-02-15 23:01:58

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

我使用默认路由定义:

{controller}/{action}/{id}

其中id = UrlParameter.Optional。据我所知,这意味着当id不属于URL时,此路由值将不会存在于RouteValues字典中。

所以这看起来也很可能(都是GET):

public ActionResult Index() { ... } // handle URLs: controller/action

public ActionResult Index(int id) { ... } // handle URLs: controller/action/id

当缺少id时,将执行第一个操作,但是当存在id时,第二个操作将执行。很好,但它不起作用。它无法解决行动。

我该如何做到这一点?

我正在考虑编写一个自定义操作方法选择器属性,如:

[RequiresRouteValue(string valueName)]

这样可以使用这种动作方法。但这是唯一的方法吗? 我有什么可以内置的内容吗?

2 个答案:

答案 0 :(得分:1)

使用:

[HttpGet]
public ActionResult Index() { ... } // handle URLs: controller/action

[HttpPost]
public ActionResult Index(int id) { ... } // handle URLs: controller/action/id

或者只有一个可以为空的参数:

public ActionResult Index(int? id) { ... } // handles both instances

编辑: 这样的事情会起作用吗?

            routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/", // URL with parameters
            new { controller = "Login", action = "Index" } // Parameter defaults
        );

        routes.MapRoute(
            "DefaultWithValue", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Login", action = "Index", id = UrlParameter.Optional } // Parameter defaults
        );

答案 1 :(得分:1)

除了无法确定操作的异常之外,非常清楚操作首先被解析然后数据绑定器发挥作用并检查操作的参数并尝试将数据绑定到它们。有一个完美的感觉。

这很有道理。首先尝试将数据绑定到所有可能的类型并查看我们获得的内容然后寻找适当的操作是没有意义的。那几乎是不可能的。

因此。由于动作选择是这里的问题,我想最好(也是唯一)解决这个问题的方法(如果我不想使用多方面的单一动作方法)是写一个自定义动作方法选择器属性

您可以阅读所有详细信息并在我的博客上获取代码:
Improving Asp.net MVC maintainability and RESTful conformance