ASP.NET MVC 2 RC2 Routing - How to clear low-level values when using ActionLink to refer to a higher level?

為{幸葍}努か 提交于 2019-12-01 11:16:33

In your constraint you can delete any routeValues you do not need.

values.Remove("itemId");

Then create a class that inherits from IRouteConstraint.

Then in the Match method clear your route value and return true (indicates the route matches).

public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{

    values.Remove("itemId");    
    return true;
}

then in Global.asax.cs change

new { customerId = @"\d+", orderId = @"\d+" }

to

new { customerId = @"\d+", orderId = @"\d+", custom=new MyNewConstraint() }
Jab

I deleted my previous answer, didn't notice they were the same controller. Try setting itemId = string.empty. This will make the first route fail, as it requires a digit in that position.

ActionLink("Back to Index", "index", new { itemId=string.empty })

Optionally you can create a link with the name of the route "item" manually

<%= Url.RouteUrl("item", new { controller="Items", action="Index", orderId=3 ... }) %>

OK, I think I've got this to do what I want, by using RouteLink instead of ActionLink:

RouteLink("Back to Index", "items", new { action="index" })

...where the 2nd parameter is the name of the route I want to explicitly invoke.


EDIT: I didn't really want to go through all my dozens of ActionLinks and put them in this form, so instead I've modified the "item" rule to include a constraint on the {action} parameter, so that "index" does not match this route. Thus, it matches the "items" route instead - which has no itemId parameter. That seems to be a simpler way to do this, since the bulk of my code is unchanged.

Solution at the root of the problem

It seems that the optimal solution (that doesn't smell like a workaround) is the one that solves the problem where it has roots and that's in routing.

I've written a custom Route class called RouteWithExclusions that is able to define route value names that should be excluded/removed when generating URLs.

The whole problem is detailed and explained in my blog post and all the code is provided there as well. Check it out, it may help you solve this routing problem without the use of constraints but with a route that does what's required.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!