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

[NOTE: I am using ASP.NET MVC2 RC2.]

I have URLs like this:

/ customers / 123 / orders / 456 / points / index

/ customers / 123 / orders / 456 / items / 789 / change

My routing table lists the most specific routes, so I got:

// customers/123/orders/456/items/789/edit
routes.MapRoute(
    "item", // Route name
    "customers/{customerId}/orders/{orderId}/items/{itemId}/{action}", // URL with parameters
    new { controller = "Items", action = "Details" }, // Parameter defaults
    new { customerId = @"\d+", orderId = @"\d+", itemId = @"\d+" } // Constraints
);

// customers/123/orders/456/items/index
routes.MapRoute(
    "items", // Route name
    "customers/{customerId}/orders/{orderId}/items/{action}", // URL with parameters
    new { controller = "Items", action = "Index" }, // Parameter defaults
    new { customerId = @"\d+", orderId = @"\d+" } // Constraints
);

When I am on the Edit page, I need a link to the Index page. So, I use:

ActionLink("Back to Index", "index")

However, since there is an object-object identifier, this leads to the URL:

/ customers / 123 / orders / 456 / points / 789 / index

... whereas I want it to "forget" the identifier of the element and simply use:

/ customers / 123 / orders / 456 / points / index

I tried to override the item id as follows:

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

... . :

//123//456/? Itemid = 789

ActionLink "" ?


EDIT: - "", "".

EDIT: ​​ , itemId = string.empty .

+2
4

routeValues, .

values.Remove("itemId");

, IRouteConstraint.

true (, ).

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

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

Global.asax.cs

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

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

, , . itemId = string.empty. , .

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

"item"

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

, , , , RouteLink ActionLink:

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

... - , .


: ActionLinks , "item", {action}, "index" . , "items", itemId. , , , .

+1

, ( ) - , , .

I wrote my own class Routewith a name RouteWithExclusionsthat can define the names of route values ​​that should be excluded / deleted when creating URLs.

The whole problem is described in detail in the section of my blog post , and it also contains all the code. Check this out, it can help you solve this routing problem without using restrictions, but using a route that does what is required.

+1
source

Source: https://habr.com/ru/post/1758919/


All Articles