开发者

ASP.NET MVC ignore route value

I have the following route: {param1}/{param2}/{param3} and I want to bind it to action which doesn't have param1 para开发者_C百科meter (it doesn't matter for it). If I just don't define param1 parameter in the action method, route won't be chosen by ASP.NET MVC. So now I have to define param1 parameter in the action and just don't use it.

Is there any way to ignore some route values to not have to define them in action methods?


Why don't you reorder your parameters so that it goes:

        routes.MapRoute(
            //// Route name
            "myNewRoute",
            //// URL with parameters
            "{param2}/{param3}/{param1}",
            //// Parameter defaults
            new { controller = "MyController", action = "MyActionName", param2 = string.Empty, param3 = string.Empty, param1 = string.Empty });

Now if you supply only the first two parameters, it takes param2 and param3. param1 defaults to string.empty.

If you supply all three parameters, then param1, param2, and param3 will all have values.


A second approach would be to use a 2 MapRoutes. Note that I added "Custom" to the route here, to ensure that the routing engine can differentiate between this route and routes that take three parameters and should go to the default asp mvc route.

I also placed Route1 before Route2 so the routing engine, if it sees 2 parameters, would prefer this route over Route2. if you supply 3 parameters, the route will prefer Route2 over Route1 or the default mvc route.

   routes.MapRoute(
        //// Route name
        "Route1",
        //// URL with parameters
        "Custom/{param2}/{param3}",
        //// Parameter defaults
        new { controller = "MyController", action = "MyActionName", param2 = string.Empty, param3 = string.Empty });


   routes.MapRoute(
        //// Route name
        "Route2",
        //// URL with parameters
        "Custom/{param1}/{param2}/{param3}",
        //// Parameter defaults
        new { controller = "MyController", action = "MyActionName", param2 = string.Empty, param3 = string.Empty, param1 = string.Empty });
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜