ASP.NET MVC Html.ActionLink result URL - the way o

2019-02-17 08:29发布

问题:

I create an amount of actions in MVC controllers.

public ActionResult DoSmth1(string token)
public ActionResult DoAnother2(string token)

And when I have to call ActionLink..

=Html.ActionLink<SomeController>( x=> x.DoSmth(item.property), item.property)
=Html.ActionLink<AnotherController>( x=> x.DoAnother(item.property), item.property)

...it generates me different URLs:

/Some/DoSmth/stringvalue
/Another/DoAnother?property=stringvalue

Where to set the way it builds an URL? I am alr have no ideas...((


OK, a got some waylight: - if the property names are the same that used in routing schema - eg controller,action and id - the MVC will always use the route builder (/c/a/id).

That helps a little (so - name the parameter "id" as possible))

But the overall problem is still valid...


must be named the same as the token in the route

Exactly - i first had that idea.

But - now i have only default route ({controller}/{action}/{id}) but still have the URL with "property" in slashes... This is pretty weird.

  • there's also a cheater way - to create a precise route that match a given controller with it's parameter names - is seems that will be the ultimate answer - but i still don't want to do this ((

回答1:

You don't show your routes, but you're almost certainly hitting different routes in this example. The argument to your action must be named the same as the token in the route in order for the generated URL to match the route token with the lambda form of ActionLink. Anything which does not match a routing token will be appended as a query string parameter, as with your second URL. Seeing the query string parameter is strong evidence that the name you passed implicitly ("property" in this case) does not match a route token. Since you get different results with the same token name, I thereby conclude you are hitting different routes. Incidentally, I recommend building links with RouteLink instead of ActionLink, so that you can be certain of which route you will match.